【问题标题】:How to get a instance of db from node-mongo native driver?如何从 node-mongodb 本机驱动程序获取 db 实例?
【发布时间】:2013-06-19 09:23:18
【问题描述】:

考虑一下,我在主 app.js 文件本身中打开了 MongoDB 连接,并且以下代码属于它的回调:

mongodb.connect('MongoDBUrlGoesHere', function (err, db) {
   app.listen(app.get('port'), function AppListnCB() {
       console.log("Server listening on port " + app.get('port'));
   });
});

这一切都是为了在整个应用程序中只有一个数据库实例。

现在,如果我们在另一个 external.js 文件中并且需要一个相同的 db 对象,该对象已经连接。如果我们使用mongoskinmongoose,这可以很容易地完成

有人可以帮我找出如何使用本机驱动程序来完成吗?

【问题讨论】:

    标签: node.js mongodb mongoose node-mongodb-native mongoskin


    【解决方案1】:

    您可以编写一个包装器,一个存储数据库实例的新模块,类似于以下内容:

    //db.js
    var HOSTNAME = ...
    var PORT = ...
    
    var db = module.exports = {};
    var instance;
    
    db.connect = function (){
        ...
        instance = <db_instance>;
    };
    
    db.disconnect = function (){
        ...
        instance = null;
    };
    
    db.instance = function (){
        return instance;
    };
    

    现在,每次您需要数据库实例时,通过执行以下操作检索它:

    var db = require ("./path/to/db");
    db.instance ();
    

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 2017-11-15
      • 2018-10-18
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多