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.

2
  • 1
    Do you want to add that cities to every region or to this particular one (Badakhshan) ? Commented Jan 14, 2019 at 8:38
  • To particular. Thanks I did not specific where to save. Commented Jan 14, 2019 at 8:42

1 Answer 1

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 } } },
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.