gb_spectrum
gb_spectrum

Reputation: 2301

Mongoose - multiple parameters in findOne

Here is a route I have:

router.get('/home', function (req, res) {
User.findOne({_id: req.user._id}, function (err, user) {
    if (err) return next(err);
    res.render('home', {user: user});
});
});

Basically, in order for someone to view this /home page they need to be logged in, which is where User.findOne comes into play. It will search for the user in the 'user' collection; if it doesn't find the user (if the user isn't logged in), it will return an error. Otherwise, it will show them the /home page.

Now, I want to have a separate Admin section of my website where only users with admin privileges can access the page. I've tried doing something like this:

router.get('/admin', function (req, res) {
User.findOne({_id: req.user._id, admin: true}, function (err, user) {
    if (err) return next(err);
    res.render('admin', {user: user});
});
});

What I'm trying to get the code to do is to look for 2 parameters: whether the user is logged in, and whether or not in that user document their 'admin' is set to 'true'. Obviously the above code doesn't work, and I don't know how to get this to work better.

EDIT: my user schema:

var schema = mongoose.Schema;
var UserSchema = new schema ({
username: {type: String, unique: true},
email: {type: String, unique: true, lowercase: true, required: true},
password: {type: String, minlength: passMinLength, required: true},
admin: {type: Boolean, default: false},
profile: {
    firstName: {type: String, default: ''},
    lastName: {type: String, default: ''}
}
});

Upvotes: 1

Views: 7100

Answers (1)

Nivesh
Nivesh

Reputation: 2603

there is nothing wrong in the query {_id: req.user._id, admin: true} , and it should work if User.Schema contains the admin(Boolean) field also.

Besides, alternate way is to check for admin once you get the User object.

User.findOne({_id: req.user._id}, function (err, user) {

    if (err) return next(err);

    if(!user){
        //considering admin is boolean field
        if(!user.admin){
        // Not Authorised to access, do something
        }
        else{
        // User verified as Admin
         res.render('admin', {user: user});
        }
    }
    // UserId Not found, do something
});

Upvotes: 3

Related Questions