2

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:

  • Find: 'josephine doyle' --> Result: Josephine Doyle

  • Find: 'jos doyle' --> Result: Josephine Doyle

But, I want to solve this case of problems:

  • Find: 'doyle josephine' --> Result: {}
  • Find: 'do josephine' --> Result: {}
  • Find: 'doyle jo' --> Result: {}

    (Different order words doesn't work)

  • Find: 'josephine

    doyle' --> Result: {}

    (With more than one space between words doesn't work)

Any suggestions? Maybe another RegEx? Thanks!

Community
  • 1
  • 1
Aral Roca
  • 5,442
  • 8
  • 47
  • 78

1 Answers1

3

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 })
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80