0

So I'd like to order products by price - ASC and DESC, but some of the products will have a discounted:true attribute. If discounted is true sort should use discountPrice field and if fals - they should use price field.

Im using mongoose version: ^5.1.0

Here is my (not working) solution

products.find({}, {sort: { price: 1, discountPrice: 1 }})

Using those products:

{ 
 name: 'p1',
 price: 10,
 discountPrice: 5,
 discounted: true
},
{ 
 name: 'p2',
 price: 11,
 discountPrice: 8,
 discounted: false
},
{ 
 name: 'p3',
 price: 990,
 discountPrice: 6, 
 discounted: true
}

I expect the output to be: [p1, p3, p2] but the actual output is: [p1, p2, p3]

Rafał Figura
  • 5,428
  • 1
  • 15
  • 20
  • 2
    You need `aggregate()` for calculations. i.e `.aggregate([{ "$addFields": { "sortOrder": { "$subtract": [ "$price", "$discountPrice" ] } }},{ "$sort": { "discountPrice": 1 } }])` if you wanted the "difference". Your expected order though appears just to be on the "discountPrice" only so `.find({}).sort({ "discountPrice": 1 })` – Neil Lunn Mar 31 '19 at 01:29
  • 2
    If you did mean a calculation and wanted to include the `discounted` field in the logic, then something like `.aggregate([{ "$addFields": { "sortOrder": { "$cond": { "if": "$discounted", "then": { "$subtract": [ "$price", "$discountPrice" ] }, "else": "$price" } } }},{ "$sort": { "discountPrice": 1 } }])` which alternates values base on `true/false` in the field. – Neil Lunn Mar 31 '19 at 01:33

0 Answers0