Ant
Ant

Reputation: 245

nested promises node js

I read tutorial from here and I dont understand why second "insertOne" doesn`t work. Thanks for help!

var Promise=require('promise');
var MongoClient=require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url)
    .then(function(db) 
{
    db.collection('Documents').insertOne({
        Employeeid: 1,
        Employee_Name: "Petro"})
        .then(function(db1) {
            db1.collection('Documents').insertOne({
                Employeeid: 2,
                Employee_Name: "Petra"})
        })
        db.close();
    });

Upvotes: 3

Views: 665

Answers (2)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

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)
})

Upvotes: 0

Anthony Chung
Anthony Chung

Reputation: 1477

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();
        })
    });

Upvotes: 3

Related Questions