Search code examples
javascriptnode.jsmongodbexpressmern

How do I access user roles to get all instructor posts in my MERN app?


As you can see I have 2 models Post

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);

User

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);

As you can see i have 2 roles, instuctor and students. Right now I can get all posts

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',
        });
    }
}

But i want to get all posts created by instuctors. How do i implement this?

I tried to do smth like this

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'
    });
}
}

But i dont know how to access role from user, hopefully you guys can help me! Im stuck at this problem for days.


Solution

  • You need to first get users with instructor role and then you can use that info to get the list of posts created by those instructors.

    Something like this would work.

    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',
            });
        }   
    }