0

I have collection with data:

{
  "_id": { "$oid":"5c3334a8871695568817ea26" },
  "country":"Afghanistan",
  "code":"af",
  "region":[
    {
      "path":["Afghanistan"],
      "_id":{"$oid":"5c3366bd3d92ac6e531dfb43"},
      "name":"Badakhshan",
      "city":[]
    },
    ...
  ]
},

And I need to add cities (Array) inside city field. My model looks like this:

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 },
    }],
  }],
})

I send query

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

and receive the error MongoError: Cannot create field 'city' in element {region: [..... What is my mistake? I look similar topics but not found the answer.

Sergei R
  • 701
  • 4
  • 10
  • 24

1 Answers1

2

You can use the $ positional operator to indicate which element od region array should be updated, try:

Model.updateOne(
    { code: country.code, 'region.name': 'Badakhshan' },
    { $push: { 'region.$.city': { $each: savedCities } } },
)
mickl
  • 48,568
  • 9
  • 60
  • 89