如何正确链接所有涉及mongo数据库的承诺

时间:2019-01-07 00:20:14

标签: node.js mongodb promise

我是Node和Mongo的初学者,所以我需要一些帮助。我正在使用许诺和MongoDB进行练习。我想将2个插入动作链接在一起。但是,当我运行此代码文件时,出现错误:“ TypeError:无法读取未定义的属性'db'     在/ Users / jenniferzhou / Documents / 2018-2019 / MEAN Practice / Guru99 / E8 / mongopractice5.js:12:22     在process.internalTickCallback(内部/进程/next_tick.js:77:7) ” 该错误表明问题出在这行代码:“ var db = client1.db('EmployeeDB')”。但是,我不确定为什么此行将返回错误。我知道MongoClient.connect(url,{useNewUrlParser:true})返回一个诺言,但是这个诺言是否与第一个.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)
}) 

2 个答案:

答案 0 :(得分: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);
 })

每个请求结束后,您应该关闭。

而且您没有使用您导入的Promise库。

答案 1 :(得分:1)

连接和插入返回承诺。它们通过then方法链接在一起。 IMO还希望构建执行离散任务并返回承诺的函数,所以...

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