A.K.
A.K.

Reputation: 539

How to make case insensitive query in mongodb

this API is getting called for per change. it can be a number or name field. here the task is I want to search name with case-insensitively.

 router.get('/v1/branch/search/customers/:phoneNumber',authenticate , (req, res) => {
    var regex = "/^"+req.params.phoneNumber+"/", name ="/^"+req.params.phoneNumber+"$/i"; 

    Customer.find({
        subscriberId: req.user.subscriberId,$or:[{$where:regex+'.test(this.phoneNumber)'},{$where:name+'.test(this.name)'},{$where:regex+'.test(this.name)'}],
        _creator : req.user._id
      },{name:1,phoneNumber:1,_id:0}).sort({name: 1}).then((customer) => {
        res.send({'statusCode':0,'data':customer});
      }, (e) => {
        console.log(e);
        res.status(200).send({'statusCode':2,'message':e.message});
      }); 
  });

Above code is working case-insensitively only for some names not for all data. I am not getting what wrong I am doing here.

Upvotes: 1

Views: 94

Answers (1)

Vivek  Ghanchi
Vivek Ghanchi

Reputation: 232

you can use regex queries

{ "name" : { $regex: /Ghost/, $options: 'i' }

including this to your code will solve the problem of case-insensitively.

Upvotes: 2

Related Questions