Mongoose: Using custom function to convert value in query / aggregation Mongoose: Using custom function to convert value in query / aggregation mongoose mongoose

Mongoose: Using custom function to convert value in query / aggregation


Solved it with aggregation and combining operators like:

  • $addFields - for creating temporary field to keep the converted price
  • nested $switch for multiple currency cases:

    $switch: {    branches: [        {            case: { $eq: ['eur', '$price.currency'] },            then: { $multiply: ['$price.value', getRate(req.query.priceUnit.toLowerCase(), 'eur')] },         }, {            case: /* next case */         }   ],   default: '$price.value'}
  • $redact + $cond + $gte / $lte to check if converted price is in specific range (if yes: $$KEEP, otherwise: $$PRUNE)