【问题标题】:Mongoose: Trying to retrieve a document with (id) - getting NULLMongoose:尝试使用 (id) 检索文档 - 获取 NULL
【发布时间】:2019-02-26 04:16:01
【问题描述】:

所以我正在尝试使用其 ID 检索课程。我试过使用:

  • Course.findOne({ _id: __id })
  • Course.findById(id)

我不确定为什么它不起作用,我是否必须在架构中定义 _id 类型?

结果:

这是我的架构 + 功能

const courseSchema = new mongoose.Schema({
  name: { type: String, required: true, minlength: 3, max: 255 },
  category: {
    type: String,
    required: true,
    enum: ["web", "mobile", "network"]
  },
  tag: [String],
  data: Date,
  author: String,
  isPublished: Boolean,
  price: {
    type: Number,
    required: function() {
      return this.isPublished;
    },
    min: 10,
    max: 200
  },
  __v: Number
});

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

async function updateCourse(id) {
  // var __id = mongoose.Types.ObjectId(id);   // tried converting string id (?)

  console.log(id);
  // // method 1
  const course = await Course.findOne({ _id: __id });
  console.log("resulting...", course);
  if (!course) return;
  course.isPublished = true;
  course.author = "Another author";

  const result = await course.save();
  console.log("saved....", result);
}

updateCourse("5c726f6feb352743f8226239");

MongoDB:

【问题讨论】:

  • 从 Course.findOne({ _id: __id }) 中删除一个 _,使其成为 Course.findOne({ _id: _id })。另一种选择是 Course.findOne({_id: {$eq: _id}})
  • 据我回忆,当您使用代码创建文档时,_id 将是一个字符串,而不是包含字符串的对象,例如 _id: "5PkH2QD7JLXM6NGkJ" 。 (无论如何在使用流星时都会发生这种情况),并且当您在 mongo 中创建文档时,它将添加 ObjectId。因此,您可能还必须将 ObjectId 添加到查询中。
  • 删除 _ 没有用,仍然为空......我的直觉是它是否需要一个字符串或 objectId .. 很确定我尝试了两种方式 // var _id = mongoose.Types.ObjectId(id ); // 尝试转换字符串 id (?)

标签: javascript mongodb mongoose orm mongodb-query


【解决方案1】:

您不应在您的Course.findOne 通话中使用__id - 使用_id: _id

Course.findOne({_id: _id});

【讨论】:

  • 仍然返回 null...有什么想法吗?
【解决方案2】:

尝试将__id 替换为id

Course.findOne({_id: id});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-25
    • 2021-06-03
    • 2018-09-11
    • 1970-01-01
    • 2017-08-15
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多