Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    });
like image 912
Medvedev A. Avatar asked May 04 '26 20:05

Medvedev A.


1 Answers

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();
        })
    });
like image 84
Anthony Chung Avatar answered May 06 '26 10:05

Anthony Chung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!