node.js - mongo-db native 客户端中的数据库连接

标签 node.js mongodb express node-mongodb-native

我有一个express/nodeJs应用程序,它将使用mongo-db native 客户端在Mongo-db中进行持久化。现在我的问题是,我见过的大多数示例都有一个集合,因此在该 js 文件中进行连接,如下所示 tutorial (mongo-db native 客户端文档中提到)。连接代码如下:

var Db = require('mongodb').Db;

var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;

ArticleProvider = function(host, port) {
  this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
  this.db.open(function(){});
};


ArticleProvider.prototype.getCollection= function(callback) {
  this.db.collection('articles', function(error, article_collection) {
    if( error ) callback(error);
    else callback(null, article_collection);
  });
};

ArticleProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, article_collection) {
      if( error ) callback(error)
      else {
        article_collection.find().toArray(function(error, results) {
          if( error ) callback(error)
          else callback(null, results)
        });
      }
    });
};

我还保留了其他一些方法以保持较小的规模(查看上面的网址以获取完整的教程)。

我的问题是我的集合很少,因此我担心如何与数据库建立单个连接并将其用于所有集合。我还希望您可以指定如何连接到副本集以进行读取,以及如何连接到主数据库以进行写入。

或者我应该调用每个 collection.js 文件中的连接,就像上面提到的教程中所做的那样。 请帮我。

最佳答案

尝试使用singleton pattern :

在主 Express app.js 中连接到数据库并创建数据库实例:

var Database = require('database.js');

...

mongodb.connect(config.dbAddress, function (err, db) {
  if(err) {
    return console.log('Error connection to DB');
  }

  Database.setDB(db);

  app.listen(config.appPort);
});

然后在任何其他需要使用数据库的文件中再次需要database.js:

var Database = require('database.js');

...

ArticleProvider = function() {
  this.db = Database.getDB();
};

...

最后是database.js文件遵循单例模式:

/**
Database Singleton Object

database.js is used throughout the app to access the db object. Using mongodb
native drivers the db object contains a pool of connections that are used to
make requests to the db. To use this singleton object simply require it and
either call getDB() or setDB(). The idea is to use setDB in app.js just
after we connect to the db and receive the db object, then in any other file we
need the db require and call getDB
**/

var mongodb = require('mongodb');

var singleton = (function() {

  var instance; //Singleton Instance

  function init() {

    var _db; //Instance db object (private)

    //Other private variables and function can be declared here

    return {

      //Gets the instance's db object
      getDB: function() {
        return _db;
      },

      //Sets the instance's db object
      setDB: function(db) {
        _db = db;
      }

      //Other public variables and methods can be declared here
    };

  }

  return {
    //getInstance returns the singleton instance or creates a new one if
    //not present
    getInstance: function() {
      if (!instance) {
        instance = init();
      }

      return instance;
    }
  };

})();

module.exports = singleton.getInstance(); 

关于node.js - mongo-db native 客户端中的数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17420621/

相关文章:

node.js - Router.use()需要中间件功能

node.js - 删除 API 不起作用

node.js - 处理 CSV 文件困难、浏览器超时

node.js - 如何使用node.js获取图像URL数组并异步保存到s3?

javascript - 插入多对多表 - Node JS MySQL

python - 从 python 传递 mongodb 函数

javascript - 类型 'authorization' 上不存在属性 'Request'

Node.js Running Hello World on Google Cloud Platform报错部署报错

mongodb - 增长文档时 MongoDB 中的碎片

javascript - 如何创建 Mongoose Model 对象数组?