我收集了数据:
{
"_id": { "$oid":"5c3334a8871695568817ea26" },
"country":"Afghanistan",
"code":"af",
"region":[
{
"path":["Afghanistan"],
"_id":{"$oid":"5c3366bd3d92ac6e531dfb43"},
"name":"Badakhshan",
"city":[]
},
...
]
},
我需要在城市字段中添加城市(数组)。 我的模型如下所示:
const schema = new mongoose.Schema({
country: { type: String },
code: { type: String },
region: [{
name: { type: String },
path: { type: Array },
city: [{
name: { type: String },
path: { type: Array },
latitude: { type: String },
longitude: { type: String },
}],
}],
})
我发送查询
Model.updateOne(
{ code: country.code },
{ $push: { 'region.city': { $each: savedCities } } },
)
.exec()
并收到错误 MongoError: Cannot create field 'city' in element {region: [..... 我的错误是什么? 我查找类似的主题,但没有找到答案。
最佳答案
您可以使用$ positional operator要指示应更新 region
数组中的哪个元素,请尝试:
Model.updateOne(
{ code: country.code, 'region.name': 'Badakhshan' },
{ $push: { 'region.$.city': { $each: savedCities } } },
)
关于javascript - MongoDB:如何更新嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54178027/