mongoose findById using async await
我正在尝试使用async / await更新集合。 下面是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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。 谁能告诉我为什么在使用异步/等待时出现此错误。
我尝试更改
您要查找的文档中的
1 2 3 4 5 6 7 8 9 | const courseSchema = mongoose.Schema({ _id: String, name: String, author: String, tags: [String], date: Date, isPublished: Boolean, price: Number }); |
说了这么多,您可能想更新文档以将ObjectId值用于