如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接 [英] How to properly reuse connection to Mongodb across NodeJs application and modules

查看:19
本文介绍了如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读和阅读,但仍然对在整个 NodeJs 应用程序中共享相同数据库 (MongoDb) 连接的最佳方式感到困惑.据我了解,当应用程序启动并在模块之间重用时,连接应该是打开的.我目前认为最好的方法是 server.js(一切开始的主文件)连接到数据库并创建传递给模块的对象变量.连接后,模块代码将根据需要使用此变量,并且此连接保持打开状态.例如:

I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js (main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:

    var MongoClient = require('mongodb').MongoClient;
    var mongo = {}; // this is passed to modules and code

    MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
        if (!err) {
            console.log("We are connected");

            // these tables will be passed to modules as part of mongo object
            mongo.dbUsers = db.collection("users");
            mongo.dbDisciplines = db.collection("disciplines");

            console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

        } else
            console.log(err);
    });

    var users = new(require("./models/user"))(app, mongo);
    console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined

然后另一个模块 models/user 看起来像这样:

then another module models/user looks like that:

Users = function(app, mongo) {

Users.prototype.addUser = function() {
    console.log("add user");
}

Users.prototype.getAll = function() {

    return "all users " + mongo.dbUsers;

    }
}

module.exports = Users;

现在我有一种可怕的感觉,这是错误的,所以这种方法是否有任何明显的问题,如果有,如何改进?

Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?

推荐答案

您可以创建一个 mongoUtil.js 模块,该模块具有连接 mongo 和返回 mongo db 实例的功能:

You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:

const MongoClient = require( 'mongodb' ).MongoClient;
const url = "mongodb://localhost:27017";

var _db;

module.exports = {

  connectToServer: function( callback ) {
    MongoClient.connect( url,  { useNewUrlParser: true }, function( err, client ) {
      _db  = client.db('test_db');
      return callback( err );
    } );
  },

  getDb: function() {
    return _db;
  }
};

要使用它,您可以在 app.js 中执行此操作:

To use it, you would do this in your app.js:

var mongoUtil = require( 'mongoUtil' );

mongoUtil.connectToServer( function( err, client ) {
  if (err) console.log(err);
  // start the rest of your app here
} );

然后,当您需要在其他地方访问 mongo 时,例如在另一个 .js 文件中,您可以这样做:

And then, when you need access to mongo somewhere else, like in another .js file, you can do this:

var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();

db.collection( 'users' ).find();

这样做的原因是,在 node 中,当模块被 require'd 时,它们只会被加载/获取一次,所以你最终只会得到一个 _dbmongoUtil.getDb() 将始终返回相同的实例.

The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.

注意,代码未经测试.

这篇关于如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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