4

MongoDB Regex Search on Integer Value. - my question isn't duplicate. I'd like to know how search on interger value in NESTED object. I know that there is almost the same question, but mine is a little bit different. Assume I have an document in mongo collection like this:

var doc = {
    phone: 11111,
    uId: {
       internalId: 123  
    }
};

I find out that I can use regex search on integer value in mongodb with '$where' condition like in this post MongoDB Regex Search on Integer Value.

So... if I make request in a terminal:

db.myCollection.find({$where: "/^21.*/.test(this.uId.internalId)"}) - it works as expected

But if I try to send the same request with mongoose - I have an exception:

TypeError: Cannot read property 'internalId' of undefined

In other case, if I try to send something like this:

db.myCollection.find({$where: "/^21.*/.test(this.phone)"}) - it also works

Could anybody give me idea how search by number field in nested object with regex?

Code example

//This function return object wich will be passed to model.find();
//key - it is field vich I will use for search on
//value - I tnink it' clear
function numberFilter(key, value) {
    var where = '$where';
    obj[where] = '/^' + value + '.*/.test(this.' + key + ')';
    console.log('obj', obj);
    return obj;
}

Here I get object with parameters for search and pass it to find() method

var query= numberFilter('uId.internalId', 123); // won't work
var query1= numberFilter('phone', 123); // it will work

return MyModel
    .find(query)
    .then(success)
    .catch(next);

function success(data) {
    res.json(data);
}
Community
  • 1
  • 1
Vlad
  • 94
  • 1
  • 1
  • 7

0 Answers0