How do I manage MongoDB connections in a Node.js web application?

前端 未结 11 2535
旧巷少年郎
旧巷少年郎 2020-11-22 02:42

I\'m using the node-mongodb-native driver with MongoDB to write a website.

I have some questions about how to manage connections:

  1. Is it enough using

11条回答
  •  情书的邮戳
    2020-11-22 03:10

    Here is some code that will manage your MongoDB connections.

    var MongoClient = require('mongodb').MongoClient;
    var url = require("../config.json")["MongoDBURL"]
    
    var option = {
      db:{
        numberOfRetries : 5
      },
      server: {
        auto_reconnect: true,
        poolSize : 40,
        socketOptions: {
            connectTimeoutMS: 500
        }
      },
      replSet: {},
      mongos: {}
    };
    
    function MongoPool(){}
    
    var p_db;
    
    function initPool(cb){
      MongoClient.connect(url, option, function(err, db) {
        if (err) throw err;
    
        p_db = db;
        if(cb && typeof(cb) == 'function')
            cb(p_db);
      });
      return MongoPool;
    }
    
    MongoPool.initPool = initPool;
    
    function getInstance(cb){
      if(!p_db){
        initPool(cb)
      }
      else{
        if(cb && typeof(cb) == 'function')
          cb(p_db);
      }
    }
    MongoPool.getInstance = getInstance;
    
    module.exports = MongoPool;
    

    When you start the server, call initPool

    require("mongo-pool").initPool();
    

    Then in any other module you can do the following:

    var MongoPool = require("mongo-pool");
    MongoPool.getInstance(function (db){
        // Query your MongoDB database.
    });
    

    This is based on MongoDB documentation. Take a look at it.

提交回复
热议问题