javascript - MongoDB:如何更新嵌套数组

标签 javascript mongodb mongoose

我收集了数据:

{
  "_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/

相关文章:

javascript - Material-ui 对话框 : manipulating the Escape button and mouse clicking outside of the dialog

javascript - 创建rest api以从odoo erp检索数据

node.js - 自定义 MongoDB 搜索查询

java - MongoDB Java驱动程序-日期查询

javascript - Mongoose : update nested document array

javascript - 分配属性值在 Mongoose 中不起作用

javascript - <script> 里面 <script> 无法弄清楚我该怎么做

javascript - Rails Ajax JS 与 JSON 混淆

node.js - 填充多个级别不起作用

node.js - 缺少架构错误 : Schema hasn't been registered for model "Users"