使用mongoose

时间:2016-09-04 00:13:30

标签: javascript node.js mongodb mongoose subdocument

我有架构countrySchemacitySchema

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

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

我想将学校推到城市模式中的schools数组。

我已经知道countryIdcityId,所以我想它就像是

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

但这不起作用,因为我没有说明学校属于哪个城市。

查询应该如何?也许它也可能是

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

1 个答案:

答案 0 :(得分:0)

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

既然您已经拥有cityId,那么您可以简单地将学校推向学校"在城市的道路。