首页 > 解决方案 > 未填充猫鼬一对多关系

问题描述

我有一个一对多的关系,一个地方可以有多个评论。这是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 一起玩的第一个项目,所以我真的不明白我缺少什么。

标签: mongodbmongoosemongoose-schemamongoose-populate

解决方案


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

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

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


推荐阅读