相关疑难解决方法(0)

如何在NodeJs应用程序和模块中正确地重用与Mongodb的连接

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

    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 …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb node.js express

100
推荐指数
11
解决办法
4万
查看次数

标签 统计

express ×1

javascript ×1

mongodb ×1

node.js ×1