繁体   English   中英

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

[英]Using mongoDB in Node.JS web application

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM