You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB嵌套关联查询时comments下created_by无法填充用户对象如何解决

修复方案

你的代码存在两个问题,修改后即可正常嵌套填充字段:

问题1:嵌套populate写法错误

你分开写两次populate的方式无法识别数组元素内的关联字段,需要把created_by的填充规则嵌套到comments的填充配置中。

问题2:回调函数位置错误

你在findOne参数中直接传入了回调,此时查询会立刻执行,后续链式调用的populate配置根本不会生效,需要把执行逻辑放到所有populate配置之后。

修正后的代码:

ContentModel.findOne({
  post_id: args.post_id,
  post_type: args.post_type
})
.populate({
  path: 'comments',
  // 嵌套填充comments内部的created_by字段
  populate: {
    path: 'created_by',
    model: UserModel,
    // 可选:过滤用户敏感字段,只返回需要的用户信息,避免返回token这类数据
    select: 'display_name avatar email'
  }
})
.then(rslt => resolve(rslt))
.catch(err => reject(err))

可选简化写法:

如果你使用的是Mongoose 5.0以上版本,且已经在commentScheme的created_by字段里定义了ref: 'User',也可以不用显式写嵌套配置,Mongoose会自动识别层级关联:

ContentModel.findOne({
  post_id: args.post_id,
  post_type: args.post_type
})
.populate('comments')
.populate('comments.created_by')
.then(rslt => resolve(rslt))
.catch(err => reject(err))

修改后再执行查询,comments数组中的created_by字段就会正常填充为对应的用户文档对象。


内容的提问来源于stack exchange,提问作者Boby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:15:08