0

I am using Loopback node js framework with MongoDB. Here I am checking if a field contains a given string or not

    user.find({
       where: {
        or: [{
         mobile: {
           "regexp": '/' + data.search + '/i'
         },
         contacts:{
           "regexp": '/' + data.search + '/i'
         }}]

      }
   }, function(err, mobileResult) {
    if (err) {
            callback(err, null);
    } else {
    .......
    .......
    }
  });

this one works with string type field contacts but not with number field mobile.

I tried answers from these post but it didn't worked for me.

Sachin Chavan
  • 276
  • 6
  • 13
  • Do not use `'/'` and `'/i'`, pass the case insensitive modifier via `$options`. – Wiktor Stribiżew Aug 16 '17 at 13:07
  • 1
    I tried but I think, It differs with loopback, It's showing `MongoError: unknown operator: $$regex`.@WiktorStribiżew please read post once again. – Sachin Chavan Aug 16 '17 at 13:19
  • @WiktorStribiżew, In post I have already given the link of same answer, but It didn't worked, please remove tag duplicate. – Sachin Chavan Aug 16 '17 at 13:21
  • 1
    I am checking... Did you use `$regex : new RegExp(data.search, "i")`? BTW, you provided a different link in your answer. – Wiktor Stribiżew Aug 16 '17 at 13:22
  • 1
    Yes I tried that too, that link is having more answers – Sachin Chavan Aug 16 '17 at 13:23
  • 1
    [Regular expressions](https://en.wikipedia.org/wiki/Regular_expression#Basic_concepts) match patterns in strings. If you need to do pattern matching I'd suggest storing your `mobile` values as strings instead of numbers. – Stennie Aug 17 '17 at 02:56

1 Answers1

2

I think you can use this solution:

  1. Using aggregate for querying your data:

MongoDB aggregation on Loopback

  1. Using this awesome way to search on a number in MongoDB: (Second Answer)

MongoDB Regex Search on Integer Value

I also agree with @Stennie which commented:

Regular expressions match patterns in strings. If you need to do pattern matching I'd suggest storing your mobile values as strings instead of numbers.

Maryam Saeidi
  • 1,215
  • 1
  • 18
  • 29