Aral Roca
Aral Roca

Reputation: 5889

Moongose MongoDB: LIKE operator in search

After read some solutions to use "LIKE" in Mongoose:

Mongoose.js: Find user by username LIKE value

How to query MongoDB with "like"?

Mongodb dynamic like operator

I'm using this code to simulate "SQL LIKE" in Mongoose:

Find: 'joseph' --> Result: Josephine Doyle

var word = 'joseph';

User
    .find({name: new RegExp(word, 'i')})
    .sort('-created')
    .exec(function(err, users){
        if (err) {
            console.log(err);
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(users);
        }
    });

The result of this is the user Josephine Doyle, OK.

Now I want to use the same code, but with this word to search:

Find: 'josephine do' --> Result: Josephine Doyle

var word = 'josephine do';

OK, works too...

More examples than works:

But, I want to solve this case of problems:

Any suggestions? Maybe another RegEx? Thanks!

Upvotes: 2

Views: 871

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32118

You can do this by splitting the string and searching each word using $and.

Something like:

var name = 'doyle josephine';

var toSearch = name.split(" ").map(function(n) {
    return {
        name: new RegExp(n.trim(), 'i')
    };
});

User
    .find({ $and: toSearch })

Upvotes: 3

Related Questions