K
K
kushnirukd2017-11-12 16:14:39
MongoDB
kushnirukd, 2017-11-12 16:14:39

How to properly search through an array of objects in mongoose?

There are documents like this:

{
    "_id" : -1340306864,
    "name" : "123",
    "prices" : [ 
        {
            "name" : "",
            "price" : 123231
        }
    ]
}
{
    "_id" : -1341439031,
    "name" : "123",
    "prices" : [ 
        {
            "name" : "123",
            "price" : 1.123
        }, 
        {
            "name" : "321",
            "price" : 0.1
        }
    ]
}

You need to sort by minimum and maximum prices, the query looks like this:
Product.find({name : {$regex : ".*"+filters.name+".*"}, "prices.price": {$gte : filters.price.min|| 0, $lte: filters.price.max || 9999999}}, {description: false}, (err, data) => {
                if(err) return callback(err, null);
                return callback(null, data);
            }).limit(productsInPage).skip(filters.skipNumber);

When the variables filters.price.minand filters.price.maxare equal null, everything works fine, otherwise, when at least one variable is not equal, it nulldisplays an empty array. filters.price.minand filters.price.max100% number.
What's my mistake ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2017-11-15
@kushnirukd

db.test.find({prices: {$elemMatch: {price: {$gte: 0.2, $lte: 2}}}})
https://docs.mongodb.com/manual/reference/operator...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question