db.open(function(err,db){
//handle error
db.collection("book",function(err, collection){
//handle error
collection.doSomething1(... function(err, result){
//handle error
collection.doSomething2(... function(err, result){
...
})
})
})
})
但我们不会每次想做什么都写db.open,但我们必须确保db在使用时已经打开。
我们仍然不喜欢每次都在相同的代码中处理错误。
我们还可以重复使用该集合。
就这样
errorHandledDB.doSomething1("book",... function(result){
errorHandledDB.doSomething2("book",...function(result){
...
})
})
最佳答案
我使用 mongodb 实现了一个服务器应用程序进行日志记录。我使用一些提供程序类实现了数据访问,如示例所示。
provider.filelog.js
var Db= require('mongodb/db').Db,
ObjectID= require('mongodb/bson/bson').ObjectID,
Server= require('mongodb/connection').Server,
log = require('lib/common').log;
FilelogProvider = function (host, port, database) {
this.db= new Db(database, new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
FilelogProvider.prototype.getCollection= function(callback) {
this.db.collection('filelogs', function(error, log_collection) {
if (error) callback(error);
else {
log_collection.ensureIndex([[ 'created', 1 ]], false, function(err, indexName) {
if (error) callback(error);
callback(null, log_collection);
});
}
});
};
FilelogProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, log_collection) {
if (error) callback(error);
else {
log_collection.find(function(error, cursor) {
if (error) callback(error);
else {
cursor.toArray(function(error, results) {
if (error) callback(error);
else callback(null, results);
});
}
});
}
});
};
自从我使用 Grasshopper作为我的 http 中间件,我可以使用 gh 提供的 DI 功能轻松注入(inject)提供程序:
server.js
gh.addToContext({
providers: {
filelog: new FilelogProvider(conf.mongodb_host, conf.mongodb_port, conf.mongodb_database),
status: new ServerstatusProvider(conf.mongodb_host, conf.mongodb_port, conf.mongodb_database)
},
log: log
});
现在可以轻而易举地访问每个 Controller 功能中的提供程序:
gh.get('/serve', function() {
this.providers.filelog.findAll(function(err, res) {
// access data here
});
});
这个实现非常特定于 Grasshopper(因为它使用 DI),但我想你会明白的。我还使用 express 和 mongoose 实现了一个解决方案,您可以找到它 here .此解决方案比使用 native 驱动程序更简洁,因为它公开了要针对数据库使用的模型。
更新
只是为了它:如果您真的想坚持 DRY 原则,请停止自己修改 ORM 实现并使用 Mongoose .如果您需要 Map/Reduce 等特殊功能,您仍然可以使用 native 驱动程序(Mongoose 是在该驱动程序上构建的)。
关于mongodb - 使用 node-mongodb-native 时如何保持 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139429/