skip to Main Content

I have this schema:

const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    mobile: {
        type: Number,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    roles: {
        type: String,
        required: true,
        enum: ["admin", "user", "student", "instructor"],
        default: "user",
    }
});

And I am trying to find all users that have roles that includes "student", users can have multiple roles like ["user", "admin"] or ["admin", "student", "instructor"] or ["student"] or ["user"] or ["user", "instructor"], etc

2

Answers


  1. Chosen as BEST ANSWER

    const User = require("@models/user");
    
    const students = await User.find({ roles: /student/i });


  2. A standard Model.find({ key: value }) in MongoDB works the same way for an array as per the docs Query an Array for an Element so this will work:

    const users = await User.find({ roles: "student" });
    

    This will find the following documents:

    { firstName: "Bob", lastName: "Smith", roles: ["student"] }
    { firstName: "Sally", lastName: "Jones", roles: ["user", "student"] }
    { firstName: "Dave", lastName: "Brown", roles: ["user", "admin", "student"] }
    

    If roles is indeed an array, so long as student is in the array it will match.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search