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
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:This will find the following documents:
If
roles
is indeed an array, so long asstudent
is in the array it will match.