nested promises node js nested promises node js mongodb mongodb

nested promises node js


You have two asynchronous actions (db.insertOne) happening.

Therefore, you should have a .then after your second insertOne and close your connection

Code should look like this

{    db.collection('Documents').insertOne({        Employeeid: 1,        Employee_Name: "Petro"})        .then(function(db1) {            db1.collection('Documents').insertOne({                Employeeid: 2,                Employee_Name: "Petra"})        }).then(function(db2) {              db.close();        })    });


See comments

MongoClient.connect(url)    .then(function(db) {        // you need a return statement here        return db.collection('Documents').insertOne({            Employeeid: 1,            Employee_Name: "Petro"        })            .then(function(record) {                 // another return statement                // try db instead of db1                return db.collection('Documents').insertOne({                    Employeeid: 2,                    Employee_Name: "Petra"                })            })        .then(function() {            // move the close here            db.close();        })})// Add an error handler.then(null, function(error){  console.log(error)})