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

如何在MERN应用中通过用户角色获取所有讲师发布的帖子?

解决方案

你的核心问题是直接在Post模型上筛选不存在的role字段——role属于User模型,Post仅通过user字段关联用户ID,因此需要通过关联查询实现筛选。以下是两种可行方案:

方案一:先获取讲师ID集合,再筛选对应帖子

先从User模型中查询所有讲师的ID,再用这些ID匹配Post的user字段:

export const getAllByTeacher = async(req, res) => {
  try {
    // 获取所有讲师的ID
    const instructors = await UserModel.find({ role: "instructor" }, "_id");
    const instructorIds = instructors.map(user => user._id);

    // 筛选讲师发布的帖子并关联用户信息
    const posts = await PostModel.find({ user: { $in: instructorIds } })
      .populate('user')
      .exec();

    res.json(posts);
  } catch (e) {
    console.log(e);
    res.status(500).json({
        message: '无法获取讲师帖子'
    });
  }
}

方案二:使用MongoDB聚合管道(高效关联查询)

通过聚合管道的$lookup关联User集合,直接在聚合流程中完成筛选:

export const getAllByTeacher = async(req, res) => {
  try {
    const posts = await PostModel.aggregate([
      // 关联User集合,注入用户信息到userInfo字段
      {
        $lookup: {
          from: "users", // MongoDB集合名,通常为模型名小写复数
          localField: "user",
          foreignField: "_id",
          as: "userInfo"
        }
      },
      // 将userInfo数组转为单个对象(每个帖子仅关联一个用户)
      { $unwind: "$userInfo" },
      // 筛选用户角色为讲师的帖子
      { $match: { "userInfo.role": "instructor" } },
      // 重构字段,保持和原接口输出格式一致
      {
        $project: {
          title: 1,
          text: 1,
          tags: 1,
          viewsCount: 1,
          imageUrl: 1,
          user: "$userInfo",
          createdAt: 1,
          updatedAt: 1,
          comments: 1
        }
      }
    ]);

    res.json(posts);
  } catch (e) {
    console.log(e);
    res.status(500).json({
        message: '无法获取讲师帖子'
    });
  }
}

额外修正点

  1. 你尝试的代码存在拼写错误:instuctor应为instructor;
  2. User模型中的isIsntructor方法有两处错误:方法名拼写错误(应为isInstructor),判断字符串多了空格("instructor "要改为"instructor")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 11:22:53