Sunday, 23 April 2017

How to Reuse Mongo Db Connection Object in different module

I want to use MongoDB connection object to different module. Problem is whenever my app.js run it should get instantiate then i can pass to other function of module. Basically Mongo connection should be create only 1 time,

Currently i am using this code whenever we want to call MongoDb.How we can reuse MongoDb connection object outside of callback function.

var mongodb = require("mongodb");

mongodb.MongoClient.connect(url, function (err, db) {
    if (err) {
        console.log(err);
        process.exit(1);
      }
     // Save database object from the callback for reuse.
     console.log("Database connection ready");
});

//let say here i want to use 
db.collection("cname").find({}) //but i am getting db as undefined.



via Aakash Kag

No comments:

Post a Comment