我正在尝试使用Mongoose更新MongoDB中具有的对象,但出现错误TypeError: course.save is not a function
。我可以创建并找到“课程”对象。
我严格按照课程中的说明进行操作,并尝试进行故障排除,但无济于事!
知道这里发生了什么吗?
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', {
useNewUrlParser: true
})
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
isPublished: Boolean
});
const Course = mongoose.model('Courses', courseSchema);
async function createCourse() {
const course = new Course({
name: 'Course 1',
author: 'Mosh',
tags: ['angular', 'frontend'],
isPublished: true
});
const result = await course.save(); // neccesarily async
console.log(result);
}
// createCourse();
async function updateCourse(id) {
const course = Course.findById(id);
if (!course) return;
course.isPublished = true;
course.author = 'Another Author';
const result = await course.save();
console.log(result);
}
updateCourse('5c1a528838633f2f80379061');
答案 0 :(得分:2)
我认为这是因为您的查找是异步的,并且没有这样的“等待”您就无法使用查找方法:
const course = await Course.findById(id);
希望有帮助。