Setting up singleton connection with node.js and mongo

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

    Here's one way to do it. You can put your database connection details in a small module, initialize it when your app starts up, then use that module from any other modules that need a database connection. Here's the code I've been using and has been working for me in a rather simple internal application.

    file: DataAccessAdapter.js

    var Db = require('mongodb').Db;
    var Server = require('mongodb').Server;
    var dbPort = 27017;
    var dbHost = 'localhost';
    var dbName = 'CatDatabase';
    
    var DataBase = function () {
    };
    
    module.exports = DataBase;
    
    DataBase.GetDB = function () {
        if (typeof DataBase.db === 'undefined') {
            DataBase.InitDB();
        }
        return DataBase.db;
    }
    
    DataBase.InitDB = function () {
        DataBase.db = new Db(dbName, new Server(dbHost, dbPort, {}, {}), { safe: false, auto_reconnect: true });
    
        DataBase.db.open(function (e, d) {
            if (e) {
                console.log(e);
            } else {
                console.log('connected to database :: ' + dbName);
            }
        });
    }
    
    DataBase.Disconnect = function () {
        if (DataBase.db) {
            DataBase.db.close();
        }
    }
    
    DataBase.BsonIdFromString = function (id) {
        var mongo = require('mongodb');
        var BSON = mongo.BSONPure;
        return new BSON.ObjectID(id);
    }
    

    Then from server.js, when your application is starting up:

    // Startup database connection
    require('./DataAccessAdapter').InitDB();
    

    And when you need to use the database, for example in your "Cat.js" file, you could do something like this:

    var dataAccessAdapter = require('./DataAccessAdapter');
    
    var Cat = function () {
        if (!Cat.db) {
            console.log('Initializing my Cat database');
            Cat.db = dataAccessAdapter.GetDB();
        }
        if (!Cat.CatCollection) {
                console.log('Initializing cats collection');
            Cat.CatCollection = Cat.db.collection('Cats'); // Name of collection in mongo
        }
        return Cat;
    }
    
    module.exports = Cat;
    
    Cat.Name = null;
    Cat.HasFur = false;
    
    Cat.Read = function (catId, callback) {
        var o_id = dataAccessAdapter.BsonIdFromString(catId);
        Cat.CatCollection.findOne({ '_id': o_id }, function (err, document) {
            if (!document) {
                var msg = "This cat is not in the database";
                console.warn(msg);
                callback(null, msg);
            }
            else {
                callback(document);
            }
        });
    }
    

    I hope this is at least a little helpful in seeing a different approach. I don't claim to be an expert and am open to some SO feedback on this, but this solution has worked well for me so far.

提交回复
热议问题