remotevision
remotevision

Reputation: 433

$or search using Mongoose

I am trying to find whether the user is entering a duplicate name and/or email address. I am new to Mongoose (and MongoDb for that matter), but based on what I have read, this appears to be correct. However, it returns true - no matter what. If I do a find for either one individually, not as an $or, it seems to work fine.

// check if user exists
var userExists = function(u, callback) {
  User.find({$or:[ {'username': u.username}, {'email': u.email}]} , function(err,user) {
    if (err) {      // err, so not sure if user exists
        callback(1);
        return;
        } 
    if (user) { // user, so return exists
        callback(1);
        return;
        } 
    //no error, no user
    callback(0);
    });
};

thoughts?

Upvotes: 4

Views: 9578

Answers (1)

remotevision
remotevision

Reputation: 433

updated method to check for user.length instead of whether it was null. If the document is not found by Mongoose (or MongoDB), it does not return null.

// check if user exists
var userExists = function(u, callback) {
  User.find({$or:[ {'username': u.username}, {'email': u.email}]} , function(err,user) {
    if (err || user.length > 0) {     // user does not come back null, so check length
        callback(1);
        return;
    } 
    //no error, no user
    callback(0);
  });
};

Upvotes: 6

Related Questions