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

查看:94
本文介绍了如何在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

然后另一个模块模型/用户看起来像:

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:

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

var _db;

module.exports = {

  connectToServer: function( callback ) {
    MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
      _db = db;
      return callback( err );
    } );
  },

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

要使用它,您可以在 app.js

var mongoUtil = require( 'mongoUtil' );

mongoUtil.connectToServer( function( err ) {
  // start the rest of your app here
} );

然后,当您需要访问mongo时,您可以执行以下操作:

And then, when you need access to mongo somewhere, you can do this:

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

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

这样做的原因是在节点中,当模块为需要'd,他们只能加载/采购一次,所以你只会得到一个 _db mongoUtil.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天全站免登陆