codiaf
codiaf

Reputation: 629

Mongoose query to exclude a value from the result

I want to retrieve a users list but excluding the current user ID.

Right now I have it without the exclusion:

User.find()
  .or([
     {email: new RegExp(req.param('searchTerm'), 'i')}, 
     {displayName: new RegExp(req.param('searchTerm'), 'i')}
   ],
'displayName email profileImageURL')
  .limit(20)
  .exec(function(err, users)

How can I change the query to use the AND I need to exclude the current userID?

Thanks

Upvotes: 0

Views: 3100

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

Add an initial where call to your query chain for that:

User.find()
  .where('_id').ne(userID)
  .or([
     {email: new RegExp(req.param('searchTerm'), 'i')}, 
     {displayName: new RegExp(req.param('searchTerm'), 'i')}
   ])
  .select('displayName email profileImageURL')
  .limit(20)
  .exec(function(err, users)

The or call makes it read like the two are OR'ed together but they're actually AND'ed.

Upvotes: 3

Neil Lunn
Neil Lunn

Reputation: 151092

All you want is another condition with $ne against the _id. This can be represented in a number of ways:

Either:

User.find().where({ "_id": { "$ne": currentId })
  .or([
     {email: new RegExp(req.param('searchTerm'), 'i')}, 
     {displayName: new RegExp(req.param('searchTerm'), 'i')}
   ]).
  .select('displayName email profileImageURL')
  .limit(20)
  .exec(function(err, users) {

  });

Or:

User.find({ "_id": { "$ne": currentId })
  .or([
     {email: new RegExp(req.param('searchTerm'), 'i')}, 
     {displayName: new RegExp(req.param('searchTerm'), 'i')}
   ])
  .select('displayName email profileImageURL')
  .limit(20)
  .exec(function(err, users)

Or even just as a native data structure. It is JavaScript after all:

User.find(
    {
        "_id": { "$ne": currentId },
        "$or": [
            { "email": new RegExp(req.param('searchTerm'), 'i')}, 
            { "displayName": new RegExp(req.param('searchTerm'), 'i')}
        ],
    },
   'displayName email profileImageURL')
   .limit(20)
   .exec(function(err, users) {

   });

So you don't need the "helper" methods, which also result in longer and less flexible code. Data structures are easy to manipulate in dynamic languages like JavaScript.

Upvotes: 0

Related Questions