I have a app which has roles e.g "user,admin". In the controller I check if the user is admin "req.user.roles.indexOf('admin') > -1" to display all records otherwise display only users records. I was wondering if there is a better way of doing this or is this the way to go. Thanks
code
/**
* List of Articles
*/
exports.list = function (req, res) {
if (req.user.roles.indexOf('admin') > -1) {
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
}else {
Article.find({user:req.user._id}).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
}
};
You can also refactor out the database access bit in another method (probably in a different module - userController), which will make your code more readable. This doesn't qualify as an answer but putting all this in comment didn't look ok.