【发布时间】:2019-02-15 05:12:29
【问题描述】:
我正在尝试使用 async/await 更新集合。以下是我的代码:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mongo-exercises')
.then(() => {
console.log('Connected to MongoDB');
UpdateCourse("5a68fdd7bee8ea64649c2777");
})
.catch(error => console.error('Could not connect to MongoDB : ' + error));
const courseSchema = mongoose.Schema({
name: String,
author: String,
tags: [String],
date: Date,
isPublished: Boolean,
price: Number
});
const Course = mongoose.model('course', courseSchema);
async function UpdateCourse(id) {
console.log(`Inside Update Course. Finding ${id}`);
const course = await Course.findById(id);
console.log(`Course: ${course}`);
if(!course)
return;
course.isPublished = true;
course.author = 'Another Author';
//course.set({isPublished: true, author: 'Another Author'});
const saved = await course.save();
console.log(saved);
}
我在 mongo shell 中查询生成以下输出的集合:
在 UpdateCourse() 方法中,我将 null 作为课程的值。我确实在集合中有 id。谁能告诉我为什么在使用 async/await 时会出现此错误。
我尝试更改findById() -> findOne({_id: id})。同样的错误。我尝试更改findById() -> find({_id: id}) 在这里我得到UnhandledPromiseRejectionWarning: Unhandled promise rejection.。不明白为什么。
【问题讨论】:
-
将您的代码包装在
try/catch中,这样您就可以看到实际的错误。见javascript.info/async-await#error-handling。 -
我做到了。使用 findById() 和 findOne() 相同的问题课程设置为 Null。但是通过 find 我得到
TypeError: course.save is not a function错误。 -
使用
find你会得到错误,因为它返回一个数组。为什么你这么确定你在集合中有 id? -
如果 course 为 null 您不会遇到任何错误。
try/catch帮不了你 -
@Josh 我更新了我的问题,显示文档在集合中可用。你能解释一下如何通过它在 node.js 中的 id 来查找文档吗?我见过一些例子。即使是回调模式而不是 async/await 也会产生 null。