Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do simple mongoose findOne with multiple conditions?

How can I perform this findOne query with multiple conditions? Or a substitute method (preferrably an equally simple one) if it is not possible...

User.findOne({ 'email': email }, function (err, user) {

        if (err) {
            request.session.flash = {
                type: "danger",
                message: "Failed to log you in, error occurred."
            };
            response.redirect("/snippet/");
        }

I have tried

User.findOne({ 'email': email, 'pwd': pwd }, function (err, user) {

and

User.findOne({ 'email': email $and 'pwd': pwd }, function (err, user) {

and

User.findOne({ 'email': email}, $and: {'pwd': pwd}, function (err, user) {
like image 747
Matt Welander Avatar asked Mar 13 '23 01:03

Matt Welander


2 Answers

Try using the mongoose promise system (.exec()). The query inside .findOne() should be a single object.

User
    .findOne({email: email, pwd: pwd})
    .exec(function(err, user){
        ...
    });

Sidenote - it looks like this is for authenticating a a user login. It might be a better strategy to query just on the email, then try to match the passwords to give more depth to the error responses than a blanket 'Invalid login' type response.

User
    .findOne({email: email}) //If not found, no user with that email exists
    .exec(function(err, user){
        var hashed_pwd = hashPassword(pwd);
        if(!hashed_pwd === user.pwd){
            //If they don't match, user entered wrong password
        }
        ...
    });
like image 97
zacran Avatar answered Apr 02 '23 17:04

zacran


User.findOne({ 'email': email, 'pwd': pwd }, function (err, user) {

this syntax is correct. if this isn't returning any results, it means you didn't match any records.

my guess is that your pwd field is hashed / encrypted and that you need to run the same hash / encryption on your pwd variable before doing this findOne

like image 34
Derick Bailey Avatar answered Apr 02 '23 19:04

Derick Bailey