【问题标题】:Mongoose one-to-many relationship not being populated未填充猫鼬一对多关系
【发布时间】:2021-07-16 02:13:05
【问题描述】:

我有一对多的关系,一个地方可以有多个评论。这是 2 个架构

export const PlaceSchema = new mongoose.Schema({
  name: { type: String, required: true, unique: true },
  center: { type: [Number], required: true },
  borders: { type: [], required: true },
  reviews: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Review' }]
});

export const ReviewSchema = new mongoose.Schema({
  user: { type: String, required: true },
  city: { type: mongoose.Schema.Types.ObjectId, ref: 'Place', required: true },
  creation_date: { type: Date, required: true },
  ...
});

我有带有正确地点 ID 的评论。但是当我做一个简单的this.placeModel.find().populate('reviews').exec() 时,reviews 总是作为一个空数组返回。但是 ID 似乎没问题,如图所示(在左侧,在右侧查看)

这是我与 Mongo 一起玩的第一个项目,所以我真的看不出我缺少什么。

【问题讨论】:

  • 如果您希望使用此查询@987654326 填充评论字段,您应该检查地方文档中是否有正确的评论 ID,而不是检查您在评论文档中是否有正确的评论 ID @.

标签: mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

您的查询this.placeModel.find().populate('reviews').exec() 将以这种方式工作:

  1. places 集合中查找所有place 文档。
  2. 对于每个地点文档,遍历reviews 字段(数组类型)并在reviews 集合中搜索具有匹配id 的文档,并将数组元素替换为评论文档。
  3. 返回已在reviews 字段中填充评论文档的地点文档列表。

因此,您需要确保您的场所文档在 reviews 字段中包含正确的审核文档 ID,而不是确保您在要执行的查询的审核文档中具有正确的场所 ID。

【讨论】:

  • 哦,好吧,它就是这样工作的。好的好的,可以了,谢谢
猜你喜欢
  • 2018-01-22
  • 2018-08-23
  • 2021-04-11
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多