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