node.js - mongoose findById or findone is not wotking
问题描述
I am able to query courses in my collection and list them but am failing to update them
I have tried using the findone method as well as 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');
Am not getting any error...my console just shows successfully connected to mongodb...
解决方案
这对我有用试试这个,你的课程将被更新
async function updateCourse(id) {
await Course.find({
_id: id
})
.then(doc => {
doc.isPublished = false;
doc.author = 'Kalisha';
doc.save();
})
.catch(err => {
console.log(err);
})
}
推荐阅读
- python - Python Kivy 在 Popup 内的按钮之间切换
- python - 如何更好地清理我的数据?求朋友
- python - 使用python在包含部分字符串的目录列表中查找目录
- docker - ibmcom/mq docker 镜像向后兼容性问题
- javascript - NodeJS Buffer.write() 在写入索引 >= 100,000 时返回 0
- firebase - 当我手动打开应用程序但未点击通知时,如何清除通知?
- javascript - 记分员不会止步于得分
- c# - 连续异步 pinger 类:InvalidOperation on Progress(枚举期间修改列表)
- javascript - 将二维数组整理成带有键的对象数组
- java - AES - 在 Java 中使用密文存储 IV