为什么猫鼬不更新?

时间:2019-03-20 01:41:00

标签: node.js mongoose

我正在学习Node.js。由于这个问题,我被困在猫鼬部分。 findById(id)无法恢复我的结果,并且update()无法正常工作。我不知道为什么。

const mongoose = require("mongoose").set("debug", true);
mongoose
  .connect("mongodb://localhost/exercise")
  .then(() => console.log("Connected Successfully!"))
  .catch(err => console.error("Error: ", err.message));

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

const Courses = mongoose.model("Course", courseSchema);

async function updateCourse(id) {

  const course = await Courses.findById(id);
  course.author = "Muhib";
  const result = await course.save();
  console.log(result);
}

updateCourse("5a68fde3f09ad7646ddec17e");
//  console.log(Courses);

我收到此错误:

  

TypeError:无法将属性'author'设置为null

这是我的记录的一部分: enter image description here

btw find()有效。.

先谢谢您了:)

2 个答案:

答案 0 :(得分:1)


我解决了这个问题。
代码没有错...
首先要为什么不起作用

  

仅导入的集合会发生此问题。因为   导入的集合包含_id属性作为字符串

例如
{"_id":"5a6900fff467be65019a9001","tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"Angular Course","author":"Mosh","isPublished":true,"price":15,"__v":0}

但是猫鼬需要的是_id包裹在ObjectId中

解决方案 导入json对象时,请始终确保_id不是字符串,而是以$ oid为键,_id为值的对象


{"_id":"5a6900fff467be65019a9001","tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"Angular Course","author":"Mosh","isPublished":true,"price":15,"__v":0}
应为
{"_id":{"$oid":"5c91a66d079f4807847fcde3"},"tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"Angular Course","author":"Mosh","isPublished":true,"price":{"$numberInt":"15"},"__v":{"$numberInt":"0"}}

答案 1 :(得分:0)

尝试添加try / catch。我不确定当然..save()在没有错误的情况下工作

async function updateCourse(id) {
    try {
        const course = await Courses.findById(id);
        course.author = "Muhib";
        const result = await course.save();
        console.log(result);
    } catch (err) {
        console.log('err' + err);
    }
}

编辑1:我为此post

找到了解决方案
async function updateCourse(id) {
    try {
        const course = await Courses.findById(id).exec();//fixed at here
        course.author = "Muhib";
        const result = await course.save();
        console.log(result);
    } catch (err) {
        console.log('err' + err);
    }
}

使用 findOneAndUpdate

的另一种解决方案
try {
    var course = await Courses.findOneAndUpdate(
        {"id" : id},
        {$set: {"author" : "Muhib"}},
        {new : true}
    );
    res.status(200).json(course);
} catch (error) {
    console.log('err' + err);
}
相关问题