在Node.JS Web应用程序中使用mongoDB

3

我正在使用Node.JS编写一些简单的Web应用程序,并希望将mongoDB作为主要数据存储。
Node-mongodb-native驱动程序需要在您实际查询或存储数据之前进行链接调用(打开DB连接,认证,获取集合)。
最好在哪里进行此初始化-在每个请求处理程序中还是全局初始化应用程序时?

答:在每个请求处理程序中进行数据库初始化比全局初始化更好。这样可以确保每个请求都有自己的数据库连接,并且可以避免对其他请求的干扰。全局初始化可能会导致资源浪费和不必要的延迟。
1个回答

2

你最好将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!)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接