node.jsmongodb-nodejs-driver

how to use Mongodb one instance to different-different module in node.js


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.


Solution

  • 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