node.js - 为什么 Mongoose 不更新?

标签 node.js mongoose

我正在学习 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

这是我记录的一个片段: enter image description here

顺便说一句 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/

相关文章:

json - 客户端生成的 JSON 存储在 MongoDB 服务器端,application/json 无法正确解析?

javascript - 查询ISO格式的日期问题

node.js - Mongoose 多更新

node.js - 如何将 Slack 机器人扩展到 1000 个团队

node.js - 如何在 Node.js 中每 2 秒打印 "Hello world"10 秒?

node.js - 无法在 Node.js 中销毁 Twitter 流

node.js - NestJS - 每个模块使用多个 MongoDB 连接

node.js - Mongoose 更新查询不适用于 Node.js

javascript - Mongoose 子文档 : cannot call method call to of undefined

node.js - 和内部条件或条件 Mongoose