我可以查询我的收藏中的类(class)并列出它们,但无法更新它们
我尝试过使用 findone 方法以及 findById
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises', {useNewUrlParser: true})
.then(() => console.log(' Successfuly connected to mongodb...'))
.catch(err => console.error('Ooops! something went wrong', err));
const courseSchema = new mongoose.Schema({
name: String,
tags: [ String ],
author: String,
isPublished: Boolean,
price: Number,
date: {type: Date, default: Date.now}
});
const Course = mong.model('Course', courseSchema);
async function updateCourse(id) {
const course = await Course.findById(id);
if (!course) return;
course.isPublished = false;
course.author = 'Kalisha';
// course.set({
// isPublished: true,
// author: 'Kalisha Malama'
// });
const result = await course.save();
console.log(result);
}
updateCourse('5a68fe2142ae6a6482c4c9cb');
我没有收到任何错误...我的控制台仅显示已成功连接到 mongodb...
最佳答案
为什么不使用findOneAndUpdate
await Course.findOneAndUpdate({_id:id},{$set:{isPublished:false,author:"Kalisha"}}).exec()
请记住使用.exec()
,如果您希望返回更新的文档,请使用{new:true}
关于node.js - mongoose findById 或 findone 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55770712/