如何使用 Mongodb 一个实例到 node.js 中的不同模块

问题描述

我在 node.js 中使用 mongodb 数据库和 mongodb 模块。 我想知道如何将一个 mongodb 实例用于不同的模块?

我在 app.js 中创建了一个 mongodb 数据库实例。对于路由,我使用了另一个模块 myroutes.js,我想在 myroutes.js 中重用相同的 mongodb 实例(我已经在 app.js 中创建)。

我如何做到这一点? 我用 app.set() 试过了,但没用。

解决方法

您需要访问单例设计模式,该模式将特定对象的实例数量限制为一个。这个单一实例称为单例。

示例

var Singleton = (function () {
var instance;

function createInstance() {
    var object = new Object("I am the instance");
    return object;
}

return {
    getInstance: function () {
        if (!instance) {
            instance = createInstance();
        }
        return instance;
    }
};
})();

function run() {

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

alert("Same instance? " + (instance1 === instance2));  
}

对于 MongoDB 单例,请参阅此 https://stackoverflow.com/a/44351125/8201020