如何填充Mongoose集合嵌套对象?问答API评论数组填充异常求助
解决Mongoose嵌套数组对象的填充问题
嘿,我能看出你遇到的问题啦——核心问题出在你的Question Schema里comments字段的定义上!
你现在的Schema里把comments定义成了单个ObjectId类型:
comments: { type: Schema.Types.ObjectId, ref: "Comment", },
但你的实际数据里comments是一个ObjectId数组,这就导致Mongoose在执行populate的时候,只会把数组的第一个元素当成单个引用去填充,剩下的元素都被忽略了,所以你只看到了第一个评论对象。
修复步骤很简单:
- 修正Schema中的comments字段定义,把它改成数组类型:
const QuestionSchema = new Schema({ slug: { type: String, required: true, }, author: { type: Schema.Types.ObjectId, ref: "User", }, title: { type: String, required: true, }, body: { type: String, required: true, }, date: { type: String, required: true }, status: { type: String, required: true, }, category: { type: Schema.Types.ObjectId, ref: "Category", }, bookmarked: Boolean, comments: [{ type: Schema.Types.ObjectId, ref: "Comment" }], // 这里改成数组形式 });
- 重启服务并重新测试你的
/questions接口,这时候populate("author category comments")就会自动填充整个comments数组里的所有评论对象了。
补充说明:
Mongoose的populate方法会严格按照你Schema里定义的字段类型处理数据:如果是单个ObjectId,就填充单个文档;如果是ObjectId数组,就填充数组对应的所有文档。你的数据结构和Schema定义不匹配,才导致了这个问题。
内容的提问来源于stack exchange,提问作者Sultan afghan
相关产品推荐
相关产品推荐

