Mongoose: Find name similar to input

Issue

I have an auto complete input box that I am working on and I am trying to make a mongoose endpoint that will get me user objects based on data from the input. The data can be incomplete, but it should still get everything that is similar. eg:

var input = "st";

// Should return a user object like this one.

var userObject = {
  name: {
    full: 'Stephen Brinkworth',
    first: 'Stephen',
    last: 'Brinkworth'
  }
};

I have looked into the issue and from what I have seen, the recommended endpoint looks like this.

User.find({name: {full: new RegExp(req.query.input, 'i')}}).exec(...);

The only problem I have is that when I use this endpoint, I consistently get back an empty array. Can anyone help me with this? Much thanks.

Solution

You’ll need to employ the use of MongoDB’s $regex query operator:

Provides regular expression capabilities for pattern matching strings in queries.

The $regex operator can be utilized using one of the following syntax as specified in the documentation:

{ <field>: { $regex: /pattern/, $options: '<options>' } }  
{ <field>: { $regex: 'pattern', $options: '<options>' } }  
{ <field>: { $regex: /pattern/<options> } }

A simple solution using the $regex operator would be:

var nameRegex = new RegExp(req.query.input);
User.find({'name.full': {$regex: nameRegex, $options: 'i'}});

Answered By – gnerkus

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.