mongodb - 未填充猫鼬一对多关系
问题描述
我有一个一对多的关系,一个地方可以有多个评论。这是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 一起玩的第一个项目,所以我真的不明白我缺少什么。
解决方案
您的查询this.placeModel.find().populate('reviews').exec()
将以这种方式工作:
place
从places
集合中查找所有文档。- 对于每个地点文档,遍历
reviews
字段(数组类型)并在reviews
集合中搜索具有匹配 id 的文档,并将数组元素替换为评论文档。 reviews
返回已用审核文档填充字段的场所文档列表。
因此,您需要确保您的场所文档在该reviews
字段中包含正确的审核文档 ID,而不是确保您在审核文档中为您要执行的查询提供正确的场所 ID。
推荐阅读
- mysql - Azure 流分析输出到 MySQL 数据库
- neo4j - 一组节点之间的 Neo4J 连接和推荐
- javascript - 为什么这些嵌套的 forEach 循环的行为是这样的?
- yii2 - 如何在 yii2 Yii:t() 中使用位置占位符;
- android - Android - Get text from one textView and set to another with Android Data Binding
- java - 为什么 songName[i]!= null 在它应该是 F 的时候评估为 T
- javascript - 添加到 D3 条形图的最后一个元素未排序
- webpack - Webpack 4:hash 和 contenthash 和 chunkhash,什么时候用哪个?
- flutter - Navigator 在 Flutter 的底部导航栏中重建父页面和目标页面
- reactjs - 反应路由器发送带有参数的 URL