0

I am a beginner at Node and Mongo so I need some help. I am practicing with chaining promises and with MongoDB. I want to chain together 2 insert actions. However, when I run this code file, I get the error: "TypeError: Cannot read property 'db' of undefined at /Users/jenniferzhou/Documents/2018 - 2019/MEAN Practice/Guru99/E8/mongopractice5.js:12:22 at process.internalTickCallback (internal/process/next_tick.js:77:7) " The error says that the problem is with this line of the code: "var db = client1.db('EmployeeDB')". However, I am unsure why this line will return an error. I know that MongoClient.connect(url, { useNewUrlParser: true }) returns a promise but is this promise in some way different from the promise returned by the first .then(...)?

var Promise = require('promise')
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017'
MongoClient.connect(url, { useNewUrlParser: true        }).then(function(client) {
     var db = client.db('EmployeeDB')
     db.collection('Employee').insertOne({
         Employeeid: 4,
         EmployeeName: "NewEmployee"
     })
    client.close()
}).then(function(client1) {
    var db = client1.db('EmployeeDB')
    db.collection('Employee').insertOne({
        Employeeid: 5,
        EmployeeName: "NewEmployee1"
    })
    client1.close()
}).catch(function(err) {
    console.log(err)
}) 
Jennifer Zhou
  • 323
  • 1
  • 7
  • 20
  • 1
    seems you dont return anything from the first `then` try to log client1 , i guess its undefined. – Constantin Guidon Jan 07 '19 at 01:22
  • 1
    In the second `.then()`, 'client1' will be undefined and `client` is out of scope. You need to read [How do I access previous promise results in a .then() chain?](https://stackoverflow.com/q/28250680/3478010). – Roamer-1888 Jan 07 '19 at 17:01

2 Answers2

1
var Promise = require('promise')
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useNewUrlParser: true}).then(function(client) {
   var db = client.db('EmployeeDB');
   db.collection("Employee").insertOne({
       Employeeid: 4,
       EmployeeName: "NewEmployee"
      }).then(function(res) {
         console.log('Document inserted');
    });

    db.collection("Employee").insertOne({
        Employeeid: 5,
        EmployeeName: "NewEmployee1"
      }).then(function(res) {
        console.log('Document inserted');
     });
 }).catch(function (err) {
    console.log(err);
 })

You should close after every request ends.

And u are not using the promise library which you have imported.

bereket gebredingle
  • 12,064
  • 3
  • 36
  • 47
  • So I guess I do not need to require('promise') then. How come I can use the then function? – Jennifer Zhou Jan 07 '19 at 21:44
  • 1
    @JenniferZhou It's a method of the object, not a static function that you would need to import (or have defined globally). – Bergi Jan 07 '19 at 22:09
1

The connection and the inserts return promises. Those are chained with the then method. It's also desirable, IMO, to build functions that do discrete tasks and return promises, so...

const MongoClient = require('mongodb').MongoClient

function mongoConnect(url) {
    return MongoClient.connect(url, { useNewUrlParser: true });
}

function mongoClose(db) {
    return db.close();
}

function insertEmployee(db, employee) {
    return db.collection('Employee').insertOne(employee);
}

function insertSomeEmployees() {
    let db;
    return mongoConnect('mongodb://localhost:27017').then(result => {
        db = result;
        return insertEmployee(db, { Employeeid: 4, EmployeeName: "NewEmployee" });
    }).then(() => {
        return insertEmployee(db, { Employeeid: 5, EmployeeName: "NewEmployee1" });
    }).then(() => {
        return mongoClose(db);
    }).catch(function(err) {
        console.log(err)
    }); 
}
danh
  • 62,181
  • 10
  • 95
  • 136
  • 1
    what is the difference between client and db? does client hold all the databases available? (is there a term for what the client holds?) – Jennifer Zhou Jan 07 '19 at 21:48
  • I copied that from the OP code, figuring it was something you needed. Most mongo client usage I've seen needs only the db from the connect call. I'll edit it to match common practice. – danh Jan 07 '19 at 21:58
  • 1
    @JenniferZhou edited. Note that this version only refers to the "Employee" collection in the db, and makes no reference to "EmployeeDB' in the OP – danh Jan 07 '19 at 22:01
  • 1
    Re the other answer: promises are native in JS now. Also note the other answer is playing a little loose with async, starting two inserts more or less simultaneously and not knowing when either one finishes. Normally, we want to do some things strictly before or after other things, so we build promise chains to control that. – danh Jan 07 '19 at 22:08