0

I'm trying to check if user exists in MongoDb. For unknown reason after I found that the user exsists and send response , it's logging me that the user does not exsists

app.post("/login", function(req, res) {

    var userName = req.body.userName;
    var pass = req.body.pass;
    console.log('')
    console.log('Try to login:')
    console.log('userName: ' + userName);
    console.log('pass: ' + pass);

    if(req.body.userName && req.body.pass) 
    {

        db.collection("customers").find({first_name:userName}, function(err, docs) {
        docs.each(function(err, doc) 
        {
          if(doc) {
            //console.log(doc);
            console.log('User Exsists')
            res.send('YES');
          }
          else {
            console.log('User Does Not Exsists')
            res.end();
          }
        })});
    }  
    else
    {
        console.log('NO')
        res.send('NO')  
    }

});

Output: (first users not exists and the second does exists)

Try to login:
userName: sdlkj
pass: lkj
User Does Not Exsists

Try to login:
userName: sivan
pass: lkj
User Exsists
User Does Not Exsists

Why after I found that the user exists I'm getting another log line which it does not found ?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471

1 Answers1

0

This is happening because you're iterating over the result cursor using each, which calls its callback one final time with a parameter value of null to signal that the cursor is exhausted.

Instead, you probably want to be using findOne here:

db.collection("customers").findOne({first_name: userName}, function(err, doc) {
  if(doc) {
    console.log('User Exsists')
    res.send('YES');
  }
  else {
    console.log('User Does Not Exsists')
    res.end();
  }
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471