首页 > 解决方案 > 无法通过 id 找到文档

问题描述

所以我正在尝试更新文档,但它不适用于 _id 但如果我使用“名称”过滤它也可以使用 FindByID 并使用 mongoose 版本 5.0.18 返回 null

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercises')
    .then(() => console.log('connected to database :)'))
    .catch(reason => console.log('Can not connect to data base',reason));

const courseSchema = mongoose.Schema({
    name: String,
    author: String,
    tags: [String],
    Date: { type:Date,default:Date.now },
    isPublished: Boolean,
    price: Number
});
const Course = mongoose.model('courses',courseSchema);

async function updateCourse(id){
  let result = await Course.update({_id: id},{
      $set:{
          author: "some random dude",
          isPublished: true
      }
  });

  console.log('result: ',result);

}

updateCourse('5a68fde3f09ad7646ddec17e');

标签: node.jsmongodbmongoose

解决方案


尝试使用

//make sure you import Course module

Course.findByIdAndUpdate(id)
.then(response=>{

})
.catch(err=>{

})

推荐阅读