gpt4 book ai didi

node.js - mongoose findById 或 findone 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:04 24 4
gpt4 key购买 nike

我可以查询我的收藏中的类(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com