首页 > 解决方案 > Mongoose - 将嵌入文档添加到现有文档时,Model.updateOne 对我不起作用

问题描述

当我在 node.js 中运行此代码时,我的嵌入文档 ID 与其他集合中的相关 ID 不匹配。

const fruitSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    rating: {
        type: Number,
        min: 1,
        max: 10,
    },
    review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const watermelon = new Fruit({
    name: "Watermelon",
    rating: 7,
    review: "Meh."
});

// watermelon.save();

const personSchema = new mongoose.Schema({
    name: String,
    age: Number,
    favouriteFruit: fruitSchema
});

const Person = mongoose.model("Person", personSchema);

const person = new Person({
    name: "John",
    age: 37,
    favouriteFruit: watermelon
});

person.save();

结果,在 MongoDB 中,我得到了,从

 db.fruits.find()
{ 
  "_id" : ObjectId("5e7444c37ce78dd238d0f994"), 
  "name" : "Watermelon", 
  "rating" : 7,
  "review" : "Meh.", 
  "__v" : 0 
  }

 db.people.find()
   { 
    "_id" : ObjectId("5e7451d971df90096974be01"), 
    "name" : "John",
    "age" : 37, 
    "favouriteFruit" :
    { 
      "_id" : ObjectId("5e7451d971df90096974be00"), 
      "name" :"Watermelon",
      "rating" : 7,
      "review" : "Meh."
    },
        "__v" : 0
    }

我想我在 Model.updateOne 方法中遗漏了一些东西。我只是想将嵌入式文档添加到另一个文档中。我只是一个初学者,所以任何链接或帮助都会很棒!谢谢!

标签: javascriptnode.jsmongodbmongoose

解决方案


为什么会有这样的行为?
您在两个应该相同的水果对象中有不同_ids 的原因是您没有将_id属性添加到水果模式中,并且因为_id是所有 MongoDB 文档的必需属性,猫鼬会帮助您自动生成new_id当它创建要发送到数据库的查询时。_id它在你运行时生成的与它在你运行时生成watermelon.save()的不同,这就是你看到两个不同的 s 的原因。_idperson.save()_id

修复:
您需要做的是将_id属性添加到水果模式(可能还有人员模式以避免进一步的意外),然后_id在将文档保存到数据库之前显式生成一个您自己。_id添加属性后的水果模式应该是这样的:

const fruitSchema = new mongoose.Schema({
    _id: mongoose.ObjectId,
    name: {
        type: String,
        required: true
    },
    rating: {
        type: Number,
        min: 1,
        max: 10,
    },
    review: String
});

并且在实例化水果模型时,_id自己添加值:

const watermelon = new Fruit({
    _id: mongoose.Types.ObjectId(), // this helps generate a unique objectId
    name: "Watermelon",
    rating: 7,
    review: "Meh."
});

推荐阅读