0

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
mandan
  • 69
  • 1
  • 11
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – 1565986223 May 30 '19 at 15:20
  • i changed the code . Still it doesnt works CreatePost(); async function CreatePost() { var dbo = await getDbConnection(); await console.log("from second function"+typeof dbo); } – mandan Jun 02 '19 at 13:53

0 Answers0