Mongoose text-search with partial string

Carsten picture Carsten · Feb 2, 2016 · Viewed 23.1k times · Source

Hi i'm using mongoose to search for persons in my collection.

/*Person model*/
{
    name: {
       first: String,
       last: String
    }
}

Now i want to search for persons with a query:

let regex = new RegExp(QUERY,'i');

Person.find({
   $or: [
      {'name.first': regex},
      {'name.last': regex}
   ]
}).exec(function(err,persons){
  console.log(persons);
});

If i search for John i get results (event if i search for Jo). But if i search for John Doe i am not getting any results obviously.

If i change QUERY to John|Doe i get results, but it returns all persons who either have John or Doe in their last-/firstname.

The next thing was to try with mongoose textsearch:

First add fields to index:

PersonSchema.index({
   name: {
      first: 'text',
      last: 'text'
   }
},{
   name: 'Personsearch index',
   weights: {
      name: {
          first : 10,
          last: 10
   }
}
});

Then modify the Person query:

Person.find({ 
    $text : { 
        $search : QUERY
    } 
},
{ score:{$meta:'textScore'} })
.sort({ score : { $meta : 'textScore' } })
.exec(function(err,persons){
    console.log(persons);
});

This works just fine! But now it is only returning persons that match with the whole first-/lastname:

-> John returns value

-> Jo returns no value

Is there a way to solve this?

Answers without external plugins are preferred but others are wished too.

Answer

knigalye picture knigalye · Jan 14, 2018

regex can help you with this.

Person.find({ "name": { "$regex": "Alex", "$options": "i" } },
function(err,docs) { 
});