如何从node-mongo本机驱动程序获取db实例? [英] How to get a instance of db from node-mongo native driver?

查看:77
本文介绍了如何从node-mongo本机驱动程序获取db实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下,我在主app.js文件本身中打开了MongoDB连接,下面的代码包含在其中:

Consider, I have MongoDB connection opened in the main app.js file itself and the following code fall in it's call back:

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

完成所有这些操作后,整个应用程序中只有一个数据库实例.

This is all done to have only one db instance across the application.

现在,如果我们在另一个external.js文件中,并且需要一个有铅的相同db对象,则该对象已连接.如果我们使用的是 mongoskin

Now, If we are in another external.js file and need a same db object which is aleady has connected. This can be done very easily if we are using mongoskin or mongoose

有人可以帮助我找到如何使用本机驱动程序吗?

Can someone help me to find how this can be done with native driver?

推荐答案

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

You could write a wrapper, a new module where you store the db instance, something similar to this:

//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;
};

现在,每次需要数据库实例时,都可以通过以下方式检索它:

Now, every time you need the db instance retrieve it by doing:

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

这篇关于如何从node-mongo本机驱动程序获取db实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆