Setting up singleton connection with node.js and mongo

前端 未结 3 1366
北荒
北荒 2020-12-02 21:57

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 MD         


        
3条回答
  •  庸人自扰
    2020-12-02 22:24

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

提交回复
热议问题