0

I'm using mongodb database in node.js with mongodb module. I want to know how to use one mongodb instance into different-different module?

I create a instance of mongodb database inside app.js. And for routing I used another module myroutes.js and I want to re-use the same mongodb instance (which I already created in app.js) inside myroutes.js.

How I do this? I tried it using app.set() but it doesn't work.

1 Answer 1

1

You need to visit the singleton design pattern which limits the number of instances of a particular object to just one. This single instance is called the singleton.

Example

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

For MongoDB singleton refer to this https://stackoverflow.com/a/44351125/8201020

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.