John
John

Reputation: 480

Search query in mongodb using regular expression

im building a website, using nodejs, expressjs, mongodb, mongoose, body-parser and etc..

basically i've created a search function, where you can search for users and basically it works, but the problem is, it is case-sensitive, i want to search for the user using case-insensitive.

I have found a solution here in stack overflow and tried it on my mongo shell. this is the command

    db.loginusers.find({
    $or: 
    [

        {"firstname": {$regex: /^PIa$/i}}, 
        {"lastname": {$regex: /^NAtUrE$/i}}

    ]
})

this works on mongoshell. so when i try to put this on my JS file,

app.post("/searchresult", function(req, res){
    var thename = req.body.thename;
    LoginUser.find({
        $or: [

            {"firstname": {$regex: /^thename$/i}},
            {"lastname": {$regex: /^thename$/i}}
        ]
    }, function(err, searchedUser){
        if(err){
            console.log(err);
            res.redirect("back");
        } else {
            res.render("searchprofile", {foundUser: searchedUser});
        }
    });
});

it is not working, eventhough i tried to put the correct case on the name it is not functioning..

my question is, do i need to do something before i use the regex on my JS file?

THank you!

Upvotes: 0

Views: 1004

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

can try it with $options:'i"

LoginUser.find({
  $or: [
    {'firstname': {$options:'i', $regex: 'PIa'}}, 
    {'lastname':  {$options:'i', $regex: 'NAtUrE'}}
  ]
})

or:

LoginUser.find({
  $or: [
    {'firstname': {$regex: /PIa/i}}, 
    {'lastname':  {$regex: /NAtUrE/i}}
  ]
})

also read docs: https://docs.mongodb.com/manual/reference/operator/query/regex/

it has some nice features like: $nin, $options: 'six'

Upvotes: 2

chridam
chridam

Reputation: 103355

Because thename is a variable, use the RegExp object constructor to create a regex instance off the variable that you can then use in your query as:

var rgx = new RegExp("^"+ thename +"$", "i");
LoginUser.find({
    "$or": [
        {"firstname": rgx },
        {"lastname": rgx }
    ]
}, callback);

Upvotes: 2

Related Questions