使用猫鼬将子文档推送到数组中

Pushing sub-sub-document to array with mongoose

本文关键字:数组 文档      更新时间:2023-09-26

我有模式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) => {
  //
});
City.findByIdAndUpdate(cityId, { $push: { 'schools': school } }, (err, city) => {});

既然你已经有了城市ID,你可以简单地将学校推到城市中的"学校"路径上。