我正在学习 Node.js。由于这个问题,我被困在 Mongoose 部分。 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: Cannot set property 'author' of null
顺便说一句 find() 有效..
提前致谢:)
最佳答案
我解决了这个问题..
代码没有任何问题...
首先是为什么它不起作用
This problem occurs with the imported collections only. Because the imported collection contains _id property as a string
例如{"_id":"5a6900fff467be65019a9001","tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z ","name":"Angular 类(class)","author":"Mosh","isPublished":true,"price":15,"__v":0}
但是 Mongoose 需要的是包裹在ObjectId中的_id
解决方案
导入 json 对象时,始终确保 _id 不是字符串,而是一个以 $oid 作为键、_id 作为值的对象
例如
{"_id":"5a6900fff467be65019a9001","标签":["角度","前端"],"日期":"2018-01-24T21:56:15.353Z","名称":“角度类(class)”,“作者”:“Mosh”,“isPublished”:true,“价格”:15,“__v”:0}
应该是{"_id":{"$oid":"5c91a66d079f4807847fcde3"},"tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"角度类(class)","author":"Mosh","isPublished":true,"price":{"$numberInt":"15"},"__v":{"$numberInt":"0"}}
关于node.js - 为什么 Mongoose 不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252368/