mongodb 如何访问用户角色以在我的MERN应用程序中获取所有讲师帖子?

rdlzhqv9  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(170)

正如你所看到的,我有2模型后

import mongoose from 'mongoose';

const PostSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    text: {
      type: String,
      required: true,
      unique: true,
    },
    tags: {
      type: Array,
      default: [],
    },
    viewsCount: {
      type: Number,
      default: 0,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    imageUrl: String,
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  },
  {
    timestamps: true,
  },
);

export default mongoose.model('Post', PostSchema);

使用者

import exp from "constants";
import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required:true,
    },
    email: {
        type: String,
        required:true,
        unique: true,
    },
    passwordHash: {
        type: String,
        required: true,
    },
    role: {
        type: String,
        enum: ["student", "instructor"],
        required: true,
      },
    avatarUrl: String,
},
{
    timestamps: true,
});

UserSchema.methods.isStudent = function () {
    return this.role == "student";
  };

  UserSchema.methods.isIsntructor  = function () {
    return this.role == "instructor ";
  };
  
export default mongoose.model('User', UserSchema);

正如你所看到的,我有两个角色,教师和学生。现在我可以得到所有的职位

export const getAll = async(req, res) => {
    try{
        const posts = await PostModel.find().populate('user').exec();

        res.json(posts);
    } catch(err){
        console.log(err);
        res.status(500).json({
          message: 'Can not get post',
        });
    }
}

但我想得到所有的职位创建的导师。我该如何实现这一点?
我试着这样做

export const getAllByTeacher = async(req, res) => {
  try {
    const posts = await PostModel.find({role: "instuctor"}).populate('user').exec();

    res.json(posts);
} catch (e) {
    console.log(e);
    res.status(500).json({
        message: 'Can not get post'
    });
}
}

但是我不知道如何从用户访问角色,希望你们能帮助我!我为这个问题纠结了好几天。

62o28rlo

62o28rlo1#

您需要首先获取具有讲师角色的用户,然后可以使用该信息获取这些讲师创建的帖子列表。
像这样的东西会工作。

export const getAllByTeacher = async(req, res) => {
    try {
        const instructors = [];
        const users = await UserModel.find({ role: "instructor" });
        users.map(u => {
            instructors.push(u._id);
        });
        const posts = await PostModel.find({ user: {$in: instructors} }).populate('user').exec();
        
        res.json(posts);
    } catch (err) {
        console.log(err);
        res.status(500).json({
          message: 'Can not get post',
        });
    }   
}

相关问题