1

I have a schema field (prices) which is an array, usually with just 1 price but sometimes with a sale price listed as the second item in the array.

I'd like to be able to query this field and return the all the products, sorted from lowest to highest (and while I'm at it, use $gt and $lt to select by range).

But my challenge is dealing with the sale price, the second value in my array. I need to be able to sort by this price, and not the 1st price if there is in fact a sale price. I don't know how to say "if (prices[1]) { use prices[1] } in my mongoose query.

UPDATE

I'm able to get almost what I want using the query below.
My problem is that when I place the bit where price.1 is false first ( the sections are demarcated by the $and) I only get results reflecting products with price.1. When I place the second one first, being that price.1 is true, I only get the opposite, products with without price.1.

Is mongoose only reading the second part of my query?

Product.find({ $and:
     [{"price.1": {$exists : false }},
     {"price.0": {$gte : req.body.lower_price}}, 
     {"price.0": {$lte : req.body.higher_price} }],
     $and : [{"price.1": {$exists: true}}, 
    {"price.1": {$gte : req.body.lower_price}},
    {"price.1": {$lte : req.body.higher_price} }]}) 
.exec(function(err, products){
    if(err){
        console.log(err)
    }
    else{
        res.send(products)
    }
});
1
  • Could you provide a test case for the above problem i.e. for some sample documents, what is your expected output for a given query? Commented Oct 17, 2016 at 18:56

1 Answer 1

1
Model.find({$or :[{"price.1": {$exists: false}}, {"price.1": {$gt : 10}}]}) //get all documents where either second element of the price array doesn't exist OR if it does it's greater than 10
    .sort("price.1") // asc. Docs without second element will come first. Use -price for desc
    .exec(function(err, res){
        if(err){
            console.log(err)
        }
        else{
            console.log(res)
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.