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

前端 未结 11 2325
旧巷少年郎
旧巷少年郎 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:23

    I have implemented below code in my project to implement connection pooling in my code so it will create a minimum connection in my project and reuse available connection

    /* Mongo.js*/
    
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/yourdatabasename"; 
    var assert = require('assert');
    
    var connection=[];
    // Create the database connection
    establishConnection = function(callback){
    
                    MongoClient.connect(url, { poolSize: 10 },function(err, db) {
                        assert.equal(null, err);
    
                            connection = db
                            if(typeof callback === 'function' && callback())
                                callback(connection)
    
                        }
    
                    )
    
    
    
    }
    
    function getconnection(){
        return connection
    }
    
    module.exports = {
    
        establishConnection:establishConnection,
        getconnection:getconnection
    }
    
    /*app.js*/
    // establish one connection with all other routes will use.
    var db = require('./routes/mongo')
    
    db.establishConnection();
    
    //you can also call with callback if you wanna create any collection at starting
    /*
    db.establishConnection(function(conn){
      conn.createCollection("collectionName", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
      });
    };
    */
    
    // anyother route.js
    
    var db = require('./mongo')
    
    router.get('/', function(req, res, next) {
        var connection = db.getconnection()
        res.send("Hello");
    
    });
    

提交回复
热议问题