我对这两个 node 都不熟悉.js和MongoDB,但我已经设法将SO和mongo的文档中的一些部分整合在一起.
Mongo documentetion给出了一个例子:
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
如果我只需要在一个地方的一个函数中使用DB,这看起来很好.搜索和阅读SO向我表明,我不应该每次都打开一个新连接,而是应该使用一个池并重用我第一次获得的数据库对象.这个答案非常丰富,但我甚至不知道如何首先获得DB对象,然后如何重用它.
假设我有 node .上面的js代码在我的应用程序中.js,然后我有不同的路由需要在db上运行不同的操作,比如:
app.post('/employee', function(req, res){
//Put req.name in database
});
app.post('/car', function(req, res){
//Put req.car in database
});
我该如何把这两个片段组合成有用的东西呢?
我在http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html08170/node-js-reuse-mongodb-reference">Node.js reuse MongoDB reference中发现了一个类似的问题,但从这个(http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html)的外观来看,我似乎应该使用MongoClient而不是db().我也不确定它是否能解决我的问题...