How to manage mongodb connections in a nodejs webapp?
这个问题的答案非常棒。我想代码来表明这一点。我已尝试过以下操作,但由于它连接了异步,因此在我想要进行数据库查询时,连接尚未就绪。我想知道别人怎么做到这一点?
'use strict';
// database stuff
var mongodb = require('mongodb'); // mongodb drivers
var MongoClient = mongodb.MongoClient; // interface
var url = 'mongodb://127.0.0.1:27017/self';
// generator flow control
var co = require('co');
// database connect function
var dbConnect = function (url) {
// get the db object
MongoClient.connect(url, {
safe: true
}, function (err, db) {
if (err) throw err;
console.log('mongodb connection successful');
return db;
});
};
var db = dbConnect(url);
// generator function with flow control
co(function* () {
console.log('starting db query');
// count documents in collection
var result =
yield new Promise(function (resolve, reject) {
if (err) reject(err);
db.collection('test').count(function (err, res) {
if (err) reject(err);
resolve(res);
});
});
// output number of documents in collection
console.log(result);
});
// more code....
我想在我的应用中随处使用变量db
。
答案 0 :(得分:0)
这可能是重用连接的一种方法。
var myDb;
//reuse connection if already created
function connect(callback) {
if (myDb === undefined) {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) { return callback(err)};
myDb = db;
callback(null, db);
});
} else {
callback(null, myDb);
}
function doDBOperation(err, db) {
// your mongodb operation through db is here
co(function* () { ...
}
connect(doDBOperation);
答案 1 :(得分:0)
您可以将数据库连接包装到promise中并在生成器中等待它
function connect() {
return new Promise((resolve, reject) => {
MongoClient.connect(url, {safe: true}, (err, db) => {
if (err) return reject(err);
resolve(db);
});
});
}
var dbConnection = connect();
co(function* () {
var db = yield dbConnection;
// your code
});