1

My model was,

var userSchema = new Schema({
    first_name : String,
    last_name : String,
    ...
});

From this, I need to do search filter option. For that I am passing name params with value.

Now I want to return the document which contains first_name == name or last_name == name

How to write the query for that?

Mattias Farnemyhr
  • 4,148
  • 3
  • 28
  • 49
Ranjith
  • 2,779
  • 3
  • 22
  • 41

1 Answers1

7
User.findOne({
    $or: [
        {first_name: name},
        {last_name: name},
    ],
}, function(err, user) {
    ...
})

Use find if you expect there to be more than one document matching name to be equal to first_name or last_name.

Mattias Farnemyhr
  • 4,148
  • 3
  • 28
  • 49
  • A text index and an according search might work, too. – Markus W Mahlberg Sep 14 '14 at 21:32
  • Not sure if it worked for Ranjith, but this approach does work (it did for me). Watch out if need to search for multiple types (like String and ObjectId), since you'll get a Cast Error for ObjectId if you pass it a non-conforming string. – cjn Aug 17 '15 at 17:46