Setting up singleton connection with node.js and mongo

mongodb, node.js

Solution

Here is what uses async await on singleton. In my db.js

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

var DbConnection = function () {

    var db = null;
    var instance = 0;

    async function DbConnect() {
        try {
            let url = 'mongodb://myurl.blablabla';
            let _db = await MongoClient.connect(url);

            return _db
        } catch (e) {
            return e;
        }
    }

   async function Get() {
        try {
            instance++;     // this is just to count how many times our singleton is called.
            console.log(`DbConnection called ${instance} times`);

            if (db != null) {
                console.log(`db connection is already alive`);
                return db;
            } else {
                console.log(`getting new db connection`);
                db = await DbConnect();
                return db; 
            }
        } catch (e) {
            return e;
        }
    }

    return {
        Get: Get
    }
}


module.exports = DbConnection();

And in all modules that will use the same connection

var DbConnection = require('./db');

async function insert(data) {
    try {
        let db = await DbConnection.Get();
        let result = await db.collection('mycollection').insert(data);

        return result;
    } catch (e) {
        return e;
    }
}

Problem

Previously I used mongodb with php and to query a database I was using a singleton. This way I instantiated connection only once and then reused it: ``` class MDB{ protected static $instance; public static function use(){ if(!self::$instance) self::$instance = new MongoClient(); $db = self::$instance->selectDB('DB_name'); return $db; } } ``` Than I can create class Cats and have too methods addCat and showCats with something like this: ``` MDB::use->{'cats'}->insert([...]); MDB::use->{'cats'}->find([...]); ``` Right now I started to use mongodb with node.js. Mongodb tutorial shows me something like this: ``` var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) { if(err) { return console.dir(err); } var collection = db.collection('test'); var doc1 = {'hello':'doc1'}; collection.insert(doc1); }); ``` Which basically tells me that I have to set up all node operations as a callback inside of connect. Reading similar question the person offers: You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool. But I can not understand how should I use it (for example with my cat class)?

Original source

Related problems