javascript - 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 方法中遗漏了一些东西。我只是想将嵌入式文档添加到另一个文档中。我只是一个初学者,所以任何链接或帮助都会很棒!谢谢!
解决方案
为什么会有这样的行为?
您在两个应该相同的水果对象中有不同_id
s 的原因是您没有将_id
属性添加到水果模式中,并且因为_id
是所有 MongoDB 文档的必需属性,猫鼬会帮助您自动生成new_id
当它创建要发送到数据库的查询时。_id
它在你运行时生成的与它在你运行时生成watermelon.save()
的不同,这就是你看到两个不同的 s 的原因。_id
person.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."
});
推荐阅读
- variables - 在 Python 中声明常量
- swift - 当我勾选“包含屏幕截图”时,Xcode 如何在导出本地化时包含多个设备?
- security - Chirp 中数据有效载荷的加密
- android - 排序从firebase获得的数据我想排序以获得顶部的最新数据(第一)
- javascript - 从数组创建对象,使用递归/减少?
- javascript - 什么是 !在 VueJs 中声明 prop 时
- java - Spring Boot - Jackson 在使用列表字段时无法 POST / PUT (@ManyToMany)
- python - 如何解决 KeyError:'PUNKTSIDE_FIN'
- mysql - 如何在 SQL 中找到最频繁的对?
- java - 当我调用它时,我无法弄清楚如何在程序结束时为选择打印的包获取用户输入