Mongoose如何查询嵌套关联数据,获取带用户头像的指定帖子评论?
解决方法
你当前的查询仅做了一级user字段关联填充,需要使用Mongoose的嵌套populate能力,再填充user下关联的profilePicture字段(对应Image表)即可拿到头像url。
前置注意
首先你需要先补全Comment模型的关联字段,否则{post: req.params.postId}的查询条件会不生效:
// Comment.js 补充post关联字段 const CommentSchema = new mongoose.Schema( { // 新增post字段,关联Post表 post: { type: Schema.Types.ObjectId, ref: "Post", required: true }, user: { type: Schema.Types.ObjectId, ref: "User", }, text: { type: String, required: true, trim: true, }, })
正确查询写法
写法1:嵌套populate配置(推荐,可灵活控制字段返回)
const comments = await Comment.find({ post: req.params.postId }) .populate({ path: 'user', // 嵌套填充user下的profilePicture字段 populate: { path: 'profilePicture', select: 'url' // 按需只返回头像url,不需要额外字段可省略该行 } })
写法2:点路径填充(Mongoose 5+版本支持,写法更简洁)
const comments = await Comment.find({ post: req.params.postId }) .populate('user') .populate('user.profilePicture')
最终返回的评论数据中,user.profilePicture.url就是你需要的用户头像地址。
内容的提问来源于stack exchange,提问作者frankiie
相关产品推荐
相关产品推荐

