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

如何创建路由获取Mongoose Post模式中requests数组内的postedby关联数据

解决方案

你当前的代码仅配置了Post外层postedby字段的关联查询,Mongoose不会自动填充嵌套在数组内的关联字段,需要显式指定嵌套路径的填充规则。

调整后的代码(两种写法可选)

写法1:兼容所有Mongoose版本的嵌套populate写法

router.get("/acceptedpost",requireLogin,(req,res)=>{
    Post.find({postedby:req.user._id})
    // 填充外层postedby字段
    .populate("postedby","_id name")
    // 填充requests数组内部的postedby字段
    .populate({
        path: "requests",
        populate: {
            path: "postedby",
            select: "_id name"
        }
    })
    .then(accpost => {
        res.json({accpost})
    })
    .catch(err => {
        console.log(err)
    })
})

写法2:Mongoose 5.9+版本支持的点语法简化写法

可以直接通过字段.嵌套字段的格式指定要填充的路径,代码更简洁:

router.get("/acceptedpost",requireLogin,(req,res)=>{
    Post.find({postedby:req.user._id})
    .populate("postedby","_id name")
    .populate("requests.postedby","_id name")
    .then(accpost => {
        res.json({accpost})
    })
    .catch(err => {
        console.log(err)
    })
})

说明

  • 两种写法都可以按需调整select参数的内容,控制关联查询返回的User字段,不需要限制字段时可以删除select配置
  • 如果需要过滤requests数组的返回内容,也可以在populate配置中添加match规则实现筛选

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:15:00