Node.js Discussion Forums

There's no such thing as a stupid question. Ask. Discuss. Learn.

what is wrong with this code ?

var mydbConObj=null;

function getDbConnection()
{
MongoClient.connect(url, function(err, db) {
if (err) throw err;

return db;
});
}

function CreatePost(dbo)
{

console.log("wait without proceed");
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 displayed

TypeError: Cannot read property 'db' of undefined

My assumption
the getDbconnection is not returning the needed object.as required

can any body share their thoughts.

Mandan 4 months ago
  • Mary Shaw

    function getDbConnection()
    {
    MongoClient.connect(url,function(err,db){
    if(err)throw err;

    return db;
    });

    //your code return
    return undefined;
    }


  • Kristin

    Try this..
    function getDbConnection()
    {
    MongoClient.connect(url, function(err, db) {
    if (err){ db = ''}
    return db;
    });
    }


  • Whitelisted Links