【问题标题】:Using mongoDB in Node.JS web application在 Node.JS Web 应用程序中使用 mongoDB
【发布时间】:2012-08-12 17:07:44
【问题描述】:

我正在使用 Node.JS 编写一些简单的 Web 应用程序,并希望使用 mongoDB 作为主要数据存储。
Node-mongodb-native 驱动程序需要进行链式调用,然后才能真正查询或存储数据(打开数据库连接、身份验证、获取集合)。
在初始化应用程序时,在每个请求处理程序中还是全局范围内进行此初始化的最佳位置在哪里?

【问题讨论】:

    标签: node.js mongodb web-applications


    【解决方案1】:

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

    【讨论】:

    • 非常感谢您的解决方案!
    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多