我想在我的路线中重复使用MongoClient连接(我已经看到有使用旧连接的方法但是我想使用MongoClient而且我也想要一个单独的DB配置文件
app.js(摘录)
var route = require('route');
app.get("/", route.test);
dbconf.js
var MongoClient = require('mongodb').MongoClient;
var mongourl = 'mongodb://localhost/test';
MongoClient.connect(mongourl, function(err, db) {
if(err) console.log('Error connecting to ' + mongourl + ': ' + err);
var coll = db.collection('testcollection');
});
route.js(摘录)
exports.test = function(req, res) {
//i would like to use the connection created in dbconf.js here
}
答案 0 :(得分:1)
你可以使用承诺。这样连接只会打开一次,但您可以轻松地重用数据库对象。一个非常基本的版本看起来像这样:
database.js
var mongodb = require('mongodb'),
Q = require('q');
var MongoClient = mongodb.MongoClient;
var deferred = Q.defer();
MongoClient.connect('mongodb://localhost/test', function(err, database) {
if (err) {
deferred.reject(err);
return;
}
deferred.resolve(database);
});
exports.connect = function() {
return deferred.promise;
};
router.js
var database = require('./database');
exports.test = function(req, res) {
database.connect().then(function(db) {
var coll = db.collection('testcollection');
});
};
答案 1 :(得分:0)
你可以这样做,虽然它不使用单独的dbconf.js文件(我没有看到诚实的点,因为这样的应用程序索引将尽可能小,因为路由是分开的。 ):
./ index.js:
var MongoClient = require('mongodb').MongoClient,
routes = require('./routes'),
express = require('express')
app = new express();
MongoClient.connect('mongodb://localhost/test',function(err,db) {
if ( err ) {
// handle error
}
routes(app,db);
});
app.listen(8080);
./路由/ index.js:
testHandler = require('./test');
var routes = function(app,db) {
var testhandler = new testHandler(db);
app.get('/',testhandler.index);
}
exports = module.exports = routes;
./路由/ test.js:
var testHandler = function(db) {
this.index = function(req,res) {
db.collection('data').find().toArray(function(err,data) {
res.end(JSON.stringify(data));
});
}
}
exports = module.exports = testHandler;