【问题标题】:Is it necessary to open MongoDB connection every time I want to work with the DB?每次我想使用数据库时都需要打开 MongoDB 连接吗?
【发布时间】:2016-08-01 08:04:47
【问题描述】:

在我正在使用的示例中是以下代码:

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/my_database_name';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established to', url);

    // Get the documents collection
    var collection = db.collection('users');

    //Create some users
    var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
    var user2 = {name: 'modulus user', age: 22, roles: ['user']};
    var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};

    // Insert some users
    collection.insert([user1, user2, user3], function (err, result) {
      if (err) {
        console.log(err);
      } else {
        console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
      }
      //Close connection
      db.close();
    });
  }
});

如您所见,他正在connect 函数中进行操作。我想保持模块化并将连接与数据库操作分开。

我的建议是在 db 变量上创建一个单例并重用该变量。至少那是我在 Java 中会做的,我已经习惯了。

但是,我不确定,因为在示例中他没有提出类似的建议。

【问题讨论】:

  • 正如你所说,你可以在说服务器启动时连接到数据库。对于以后的使用,您可以获取集合并继续
  • 连接的生存时间是多少?我可以让它永远打开并仅在应用崩溃时关闭吗?

标签: node.js mongodb


【解决方案1】:

如果您想要任何一种可扩展性,我建议您不要维护一个连接。

有许多连接池等选项,但大多数花时间使用 Node 和 MongoDB 的人最终会在某个时候转向 Mongoose。

除了添加一个不错的模式层之外,它还提供了连接抽象,因此您可以通过调用mongoose.connect() 默认为共享连接,或者您可以通过调用mongoose.createConnection() 创建多个连接或参与连接池。在这两种情况下,您都无需回调即可调用它,并且 mongoose 机器会将后续对模块的调用推迟到建立连接之后,因此您的代码不必关心。

您的用例可能如下所示:

// in your app.js or server.js file
var mongoose = require('mongoose');
mongoose.connect(config.db.url); // assuming you have some module that handles config variables

然后在 ./models/user.js 中

const mongoose = require('mongoose'),
         Schema   = mongoose.Schema;

   const UserSchema = new Schema({
      name: String,
      age: Number,
      roles: [String]
   });
   mongoose.model('User',UserSchema);

最后,让我们说一个种子函数来创建您的初始一批用户:

const mongoose = require('mongoose'),
      User     = mongoose.model('User');

// create some users
var user1 = new User({name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']});
var user2 = new User({name: 'modulus user', age: 22, roles: ['user']});

user1.save(console.log);
user2.save(console.log);

【讨论】:

  • 太棒了,这正是我所需要的!谢谢。
  • 没问题;决定添加一些示例代码,希望对您有所帮助。
【解决方案2】:

我相信保持单一连接是最好的,正如another thread 中提到的那样:

node-mongodb-native says中的primary committer

当您的应用启动并重用 db 对象时,您打开一次 MongoClient.connect。它不是一个单例连接池,每个 .connect 都会创建一个新的连接池。所以打开它一次,[d] 在所有请求中重复使用。

【讨论】:

    【解决方案3】:

    说在服务器启动时启动 mongo 连接。

    Server.js:

    ...
            var db = require('./db');//require db.js
            db.openMongoConnection(function(error)
            {
                if(error)
                {
                    console.log(error);
                    console.log("cannot make the connection with database");
                }
                else
                {
                   server.listen(7400);//say ur server listening on 7000 port
                }
            }
    

    db.js

        var db1;
        var MongoClient = require('mongodb').MongoClient;
         exports.openMongoConnection = function(callback)
         {
                MongoClient.connect(<YourUrl1>,function(err,dbInstance)
                {
                    if(err)
                    {
                        callback(err);
                    }
                    else
                    {
                        db1 = dbInstance;
                        callback(null);
                    }
                });
         };
    
    
    exports.getCollection = function(collectionName, callback){
      dbInstance.collection(collectionName, function(err, collectionInstance){
        if(err)
        {
           callback(err);
        }
        else
        {
           callback(null, collectionInstance)
        }
      });
    }
    

    然后您可以通过要求 dbInsance 随时调用 getCollection 使用

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2015-06-10
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2016-12-19
      相关资源
      最近更新 更多