Let's say that I want to check if a logged in user has administrative privileges before doing a task. How can I achieve this asynchronously if I have to wait for the response from the mongoose function checking the database to know if the user has privileges or not?
Say I have a user model like such:
const UserSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
isadmin: {
type: Boolean,
default: false
}
});
Then I create a function for checking if the user is an administrator
function isAdmin(id) {
let is = false;
User.findById(id)
.then(user => {
if (user) {
if (user.isAdmin) {
is = true;
}
}
})
.catch(err => console.log(err));
//Now I want to wait for the findById function to resolve before returning this function
return is;
};
Then let's say I want to check if a user is an admin before doing something like deleting a comment from a post
router.delete("/post/comment/:id"),
(req, res) => {
if (!isAdmin(req.user.id)) {
return res.status(401).json({ notauthorized: "User is not admin" });
}
//Go ahead and remove content
}
);