arrays - 在嵌套数组 MongoDB 中更新或插入新数据
问题描述
我正在使用 Node JS 和 Mongoose 仅供参考。鉴于我有这样的事情: -
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat",
"favFood": [
{
"_id": 1,
"name": "steamed fish"
}
]
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse",
"favFood": [
{
"_id": 1,
"name": "cheese"
}
]
}
]
}
]
现在我知道如何获得如下所示insert
的新pet
数据:-
// new Pet Data to INSERT
let newPetData = {
name: "Butch",
category: "dog",
favFood: [
{
name: "bone"
}
]
}
// INSERT new data in DB
People.updateOne(
// push into the sub-documents - pets
{ $push: { pets: newPetData } },
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)
但是如果我有他们的(宠物的id),我怎么能插入新favFood
的数据呢?pet
id
let petID = 1 // this is the ID of pet named Tom
// this is a new favorite food of Tom to INSERT
let newFavFood = {
name: "fried fish"
}
// code to INSERT new favorite food of Tom (THIS DOES NOT WORK!)
People.updateOne(
{ "_id": petID } // id of pet 'Tom'
{ $push: { favFood: newFavFood } }, // push into the sub-documents - favFood
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)
上面的代码不起作用。我认为,如果我指定id
上面显示的宠物,{ "_id": petID }
就会产生我想要的东西。即使它返回一个message
of Successful!
。但仍然没有新记录添加到数据库本身。我正在寻找的结果如下所示:-
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat",
"favFood": [
{
"_id": 1,
"name": "steamed fish"
},
{
"_id": 2,
"name": "fried fish" // this is the new data inserted
}
]
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse",
"favFood": [
{
"_id": 1,
"name": "cheese"
}
]
}
]
}
]
有没有其他方法可以做到这一点?我必须$elemMatch
在此实施吗?如果是这样,我怎么能在这里做到这一点?
解决方案
查询部分匹配文档,而不是元素,因此{ "_id": petID }
匹配人员的_id。要匹配宠物,请使用点符号,例如{ "pets._id": petID }
然后使用位置运算符$
引用与查询部分匹配的第一个数组元素:
.updateOne(
{ "pets._id": petID },
{ $push: { "pets.$.favFood": newFavFood }}
)
推荐阅读
- tsql - 我需要帮助识别在另一个表中具有不同状态的表成员组
- batch-file - OpenCMD,同时运行.exe文件和一个命令
- android - AndroidX 迁移依赖/库
- google-app-maker - 是否可以在 Google App Maker 中应用条件格式?
- python - 带有嵌套列表的Python字典键到pandas DataFrame
- apache-spark - Zeppelin - Spark Interpreter 无法使用 CTAS(Create Table as Select ...)语句创建配置单元表
- acumatica - 有没有办法让一个新的 PXDBDecimal 字段显示为 null
- python - Python pdfminer 未正确显示 utf-8 字符
- angular - 自动发布带有 versionNumber 的新代码 Angular4
- c# - Elmah Raise() 记录内部异常