我正在使用Node.JS编写一些简单的Web应用程序,并希望将mongoDB作为主要数据存储。
Node-mongodb-native驱动程序需要在您实际查询或存储数据之前进行链接调用(打开DB连接,认证,获取集合)。
最好在哪里进行此初始化-在每个请求处理程序中还是全局初始化应用程序时?
我正在使用Node.JS编写一些简单的Web应用程序,并希望将mongoDB作为主要数据存储。
Node-mongodb-native驱动程序需要在您实际查询或存储数据之前进行链接调用(打开DB连接,认证,获取集合)。
最好在哪里进行此初始化-在每个请求处理程序中还是全局初始化应用程序时?
你最好将Mongo初始化放在请求处理程序之外,否则它将为每个服务的页面重新连接:
var mongo = require('mongodb');
// our express (or any HTTP server)
var app = express.createServer();
// this variable will be used to hold the collection for use below
var mongoCollection = null;
// get the connection
var server = new mongo.Server('127.0.0.1', 27017, {auto_reconnect: true});
// get a handle on the database
var db = new Db('testdb', server);
db.open(function(error, databaseConnection){
databaseConnection.createCollection('testCollection', function(error, collection) {
if(!error){
mongoCollection = collection;
}
// now we have a connection - tell the express to start
app.listen(80);
});
});
app.use('/', function(req, res, next){
// here we can use the mongoCollection - it is already connected
// and will not-reconnect for each request (bad!)
})