我正尝试使用LEN()=5
更新嵌套数组中的某些值,如下所示:-
嵌套数组:-
id
现在我有这样的东西:-
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat",
"favFood": [
{
"_id": 1,
"name": "steamed fish", // this will be updated
"gred": "A" // this will be updated
},
{
"_id": 2,
"name": "fried fish",
"gred": "B"
}
]
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse",
"favFood": [
{
"_id": 1,
"name": "cheese",
"gred": "C"
}
]
}
]
}
]
但是,很不幸,我收到了People.updateOne(
{ "$set": { "pets.$[petID].favFood.$[favFoodID].name" : "bbq fish",
"pets.$[petID].favFood.$[favFoodID].gred" : "A+" }
},
{
multi: true,
arrayFilters: [
{ "petID._id": 1 }, // pet with id of '1'
{ "favFoodID._id": 1 } // favFood with id of '1'
]
},
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)
的错误。而且我不知道不允许哪个"message": "\"_id\" is not allowed"
或引起错误。
我想要进行的更改或更新如下:-
_id
任何人都可以指示我上面代码中导致错误的哪一部分?
已调整 let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat",
"favFood": [
{
"_id": 1,
"name": "bbq fish", // this value was updated
"gred": "A+" // this value was updated
},
{
"_id": 2,
"name": "fried fish",
"gred": "B"
}
]
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse",
"favFood": [
{
"_id": 1,
"name": "cheese",
"gred": "C"
}
]
}
]
}
]
:-
updateOne
它可以返回People.updateOne(
{ "_id": 1,
"pets._id": 1,
"favFood._id": 1
},
{ $set: { "pets.favFood.$$.name" : "bbq fish",
"pets.favFood.$$.gred" : "A+", }
},
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)
。但是数据库中的值不变。从这里,如何调整我的代码?
答案 0 :(得分:0)
这是答案:-
updateOne
的工作代码:-
People.updateOne(
{},
{ "$set": { "pets.$[petID].favFood.$[favFoodID].name" : "bbq fish",
"pets.$[petID].favFood.$[favFoodID].gred" : "A+"
}
},
{
arrayFilters: [
{ "petID._id": 1 },
{ "favFood._id": 1 }
]
},
(err, success) => {
if(err) res.json({ message: `Unsuccessful!`, report: err })
else res.json({ message: `Successful!`, report: success })
}
)