Currently, I am using mongoDb within my express server to store user information in the following structure:
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
email: {type: String, required: true , index: { unique: true } },
isActive: {type:Boolean, default:false},
signUpDate: {type: Date, default: Date.now()},
roles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Role"
}
]
});
The 'Role' schema contains a single field called 'name'.
In order to determine if a user has admin privileges, I currently execute this code:
User.findById(req.SecureUserId).populate('roles').exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for(let roles of user.roles){
if(roles.name === 'admin'){
next();
return;
}
}
However, I believe there might be a more efficient way to query this information from my database. How can I optimize this process in mongoDB?