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

标签 node.js mongodb mongoose

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

相关文章:

Javascript 数组项被覆盖

node.js - MongoDB - 两个按顺序更新彼此重叠

mysql - 将 Cloud Function (nodejs) 连接到 CloudSQL mySQL 数据库

MongoDB, Mongoose : How to find subdocument in found document?

json - MongoDB减少嵌套

mongodb - 指定返回格式

node.js - 如何使用 Mongoose 和 NodeJS 将变量传递给聚合(匹配)?

javascript - 处理多个选择的发布请求

javascript - MongoDB:为什么 Array.find on comments(数组)属性返回未定义?

mongodb - 填充 $lookup 中的特定字段