Setting up singleton connection with node.js and mongo

前端 未结 3 1357
北荒
北荒 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:21

    I upvoted Scampbell's solution, but his solution should be enhanced imho. Currently it is not async, both InitDB and GetDB() should have a callback attribute.

    So whenever you change a database to connect, it fails, because it returns before it would have a chance to connect to the database. The bug is not present if you connect always to the same database (so return Database.db is always successful)

    This is my bugfix/enhancement to his solution:

    Database.InitDB = function (callback) {
    
      if (_curDB === null || _curDB === undefined ||_curDB === '') {
        _curDB = _dbName;
      }
    
      Database.db = new Db(_curDB,
                       new Server(_dbHost, _dbPort, {}, {}),
                                  { safe: false, auto_reconnect: true });
    
      Database.db.open(function (err, db) {
        if (err) {
            console.log(err);
        } else {
            console.log('connected to database :: ' + _curDB);
            if (callback !== undefined) {callback(db);}
        }
      });
    };
    

    The same goes to the rest of his functions. Also note the if (callback part, it allows Database.InitDB() to be called without argument in the beginning of app.js/server.js whatever is your main file.

    ((I should have written my reply as a comment to Scampbell's solution, but I don't have enough reputation to do so. Also kudos to him for his solution, was a nice starting point))

提交回复
热议问题