1.I have a function that establish db connection and returns the connection object or the db handle.It is passed as an argument to other functions that use CRUD functions.Code is written in Node js file.
wrote two function one for db connection initiate and other to use the object returned by it
// function to return the db handle
function getDbConnection()
{
var dc;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
return db;
});
}
// function to insert data
function CreatePost(dbo)
{
console.log(typeof dbo);
var mydbo = dbo.db("fb");
for(var i=0;i<25;i++)
{
postData = { pstID: ""+i, pstTitle: "Highway 37",pstTime: "100",pstdBy: "100",pstCntnt: "100"};
mydbo.collection("mypost").insertOne(postData, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
dbo.close();
});
}
}
var dbo = getDbConnection();
CreatePost(dbo);
Error shown while executing
var mydbo = dbo.db("fb");
TypeError: Cannot read property 'db' of undefined