我需要使用nodejs更新mongodb中的嵌套数组。我试过像 this但没有帮助,甚至没有抛出错误。
我的收藏是这个
{
"country_details": [
{
"cities": [
"Abbeville"
],
"_id": "5a6ec189bb68bb09105eabe8",
"countryCode": "US",
"countryName": "United States"
}
],
"deletion_indicator": "N",
"_id": "5a6ec189bb68bb09105eabe7",
"date_created": "Mon Jan 29 2018 12:09:05 GMT+0530 (India Standard Time)",
"__v": 0
}
我想更新城市,我已经尝试过
let query = {_id: "5a6ec189bb68bb09105eabe7", countryCode: "US", countryName: "United States"};
countryAndCitiesModel.collection.update(
query,
{$push: {"country_details.$.cities": "ABC"}},
(err, result)=> {
if(err){
return next(err);
}else{
return next(result);
}
});
没有获得更新,但获得结果就像是
{
"ok": 1,
"nModified": 0,
"n": 0
}
请帮忙..谢谢
最佳答案
您正在尝试匹配 countryCode
和 countryName
,它们是嵌套对象 country_details
的属性,这就是您的查询无法匹配任何内容的原因文档。要解决此问题,您应该修复字段的路径:
db.collection.update(
{_id: "5a6ec189bb68bb09105eabe7", "country_details.countryCode": "US", "country_details.countryName": "United States"},
{$push: {"country_details.$.cities": "ABC"}})
关于arrays - 无法使用nodeJs更新mongodb中的嵌套数组,并且不会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495969/