【问题标题】:MongoDB: how to update a nested array [duplicate]MongoDB:如何更新嵌套数组
【发布时间】:2019-06-08 05:39:06
【问题描述】:

我收集了数据:

{
  "_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: [..... 我的错误是什么? 我看起来类似的主题,但没有找到答案。

【问题讨论】:

  • 您想将这些城市添加到每个地区还是这个特定的地区(巴达赫尚)?
  • 特别。谢谢,我没有具体说明保存位置。

标签: javascript mongodb mongoose


【解决方案1】:

您可以使用$ positional operator 来指示应该更新region 数组中的哪个元素,试试:

Model.updateOne(
    { code: country.code, 'region.name': 'Badakhshan' },
    { $push: { 'region.$.city': { $each: savedCities } } },
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2017-09-11
    • 2019-12-07
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    相关资源
    最近更新 更多