43

I would like to query multiple fields using the same regular expression for both. In this query, I would like to accept a single text input and check both the firstName and lastName fields for results. I can query a single field just fine using the regex function in the mongoose documentation, but the syntax for an 'or' clause is giving me trouble.

var re = new RegExp(req.params.search, 'i');

app.User.find().or([{ 'firstName': { $regex: re }}, { 'lastName': { $regex: re }}]).sort('title', 1).exec(function(err, users) {
    res.json(JSON.stringify(users));
});

(I'm running mongoose 2.7.1 on node.js 0.6.12)

11
  • Syntax looks ok; can you expand on the trouble it's giving you? Commented Jul 30, 2012 at 16:42
  • Oh darn. It was some bad data. It turns out that does indeed work fine. Commented Jul 30, 2012 at 16:54
  • 2
    What if you had a person named "Joe Smith" and and someone searched for "Joe S" - no results? Commented Mar 22, 2013 at 4:04
  • 1
    @MikeCauser: Any idea how to write search query in case if someone searches for "Joe S" and get records like "Joe Smith" in result. I need to implement it but facing trouble. Commented May 20, 2014 at 7:56
  • 1
    For a partial match try var re = new RegExp('^.*' + req.params.search + '.*$', 'i'); Commented May 20, 2014 at 12:52

2 Answers 2

17

The code above works fine for a query on multiple fields. Turns out I had some bad data.

Sign up to request clarification or add additional context in comments.

Comments

0

My solution is to use $function that allows you to concatenate multiple fields and match their combined value against your regular expression.

const { search } = req.params;
var regex = new RegExp(`.*${search}.*`, 'i');

app.User.find({
    $expr: {
        $function: {
            body: `function(firstName, lastName) { return (firstName+' '+lastName).match(${regex}) }`,                        
            args: ['$firstName', '$lastName'],                
            lang: "js"
        }
    }
})
.exec((err, users) => {
    res.json(JSON.stringify(users));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.