无法使用异步函数updateCourse(id)更新数据,有帮助吗? 我想通过id更新isPublished和author属性。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises')
.then(() => console.log('Connected to mongodb...'))
.catch(error => console.error('Connection failed to mongoDB...', error))
const courseSchema = new mongoose.Schema({
tags: [String],
date: Date,
name: String,
author: String,
isPublished: Boolean,
price: Number,
});
const Course = mongoose.model('Course', courseSchema);
async function updateCourse(id) {
const course = await Course.findById(id);
if (!course) return;
course.isPublished = true;
course.author = 'Author Author';
const result = await course.save();
console.log(result);
}
updateCourse('5a68fde3f09ad7646ddec17e');
答案 0 :(得分:0)
从不带lean选项的查询中返回的文档是 MongooseDocuments ,而不是javascript纯对象。因此,您无法更新它们或使用 save()
const course = await Course.findOne({ _id: id }).lean();
if (!course) return;
course.isPublished = true;
course.author = 'Author Author';
course.save()
为什么不使用findOneAndUpdate
const updatedCourse = await Course.findOneAndUpdate(
{ _id: id },
{ $set: { isPublished: true, author: 'Author Author' } })
只需使用lean()就可以了...