猫鼬一对多关系没有被填充

问题描述

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

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

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

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

enter image description here

这是我与 Mongo 一起玩的第一个副项目,所以我真的不知道我错过了什么。

解决方法

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

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

因此,您需要确保您的地点文档在 reviews 字段中包含正确的评论文档 ID,而不是确保您在要执行的查询的评论文档中具有正确的地点 ID .