I want to use the mongodb connection in other modules also so I chose this approach. Is there any drawback or something that I should be aware of. I am going to require this file in my app.js file. or Is there any other elegant way of doing the same thing .
const uri = "mongodb://localhost";
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri, { useNewUrlParser: true });
db = null ;
client.connect().then(()=>{
db = client.db("mydb");
db.collection("users").createIndex({ mobno: 1 }, { sparse: true, unique: true });
}).catch((error)=>{
db = error;
});
while(true){
if (db!=null){
module.exports = db;
break;
}
}