MongoDB Regex Search on Integer Value in a nested object

Search for MongoDB regex by integer value . - My question is not duplicated. I would like to know how to search by interger value in a NESTED object. I know that there is almost the same question, but mine is a little different. Suppose I have a document in a collection mongoas follows:

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

I will find out that I can use search in a regular expression by integer value in mongodb with the condition "$ where", as in this post Search for regular expressions MongoDB by integer value .

So ... if I make a request in the 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: 'internalId' undefined

, - :

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

- , ?

//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;
}

find()

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);
}
+4

Source: https://habr.com/ru/post/1649541/


All Articles