0

I have schemas countrySchema and citySchema

citySchema = {
  cityName: String,
  schools: [schoolSchema]
}

countrySchema = {
  countryName: String,
  cities: [citySchema]
}

I want to push a school to the schools array in the city schema.

I already know the countryId and cityId, so I guess it's something like

Country.findByIdAndUpdate(countryId, { $push: { 'cities.schools': school } }, (err, country) => {
  //
});

but this won't work since I don't specify which city the school belongs to.

How should the query be? Maybe it could also be

Country.findOneAndUpdate({ _id: countryId, 'cities._id': cityId }, { $push: { 'cities.schools': school } }, (err, country) => {
  //
});
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

0
City.findByIdAndUpdate(cityId, { $push: { 'schools': school } }, (err, city) => {});

Since you already have the cityId , you can simply push the school to the "schools" path in the city.

  • But I have never made a model `City` from my `citySchema`. Would it be a better idea to create a model for all my schemas instead of nesting all the schemas in my `Country` model? – Jamgreen Sep 04 '16 at 08:22
  • That depends. But if you would be performing queries on your citySchema you would be better off if you have a separate document rather than an embedded one. If that is the case, then you do have to take care to remove "invalid" cities once you have removed the corresponding country. – Jimmy George Thomas Sep 04 '16 at 14:37