Home > OS >  how to modify data from model.find() before .sort() method
how to modify data from model.find() before .sort() method

Time:01-13

I want to make new field called finalPrice, finalPrice will contain basePrice - discountPrice, and i want to sort finalPrice

 // Find marketItem by item
    const itemType = req.query?.itemType?.split(',');
    marketItem = await MarketItem.find({
      $and: [
        (req?.query?.itemType
          ? {
              item: { $in: _ids },
              itemType: { $in: itemType }
            }
          : {
              item: { $in: _ids }
            },
        { $push: { finalPrice: "basePrice" - "dscountPrice" } })
      ]
  })
      .limit(limit)
      .skip(startIndex)
      .populate('item')
      .sort(
        req.query.sortPrice && req.query.sortDate
          ? { price: Number(req.query.sortPrice), createdAt: Number(req.query.sortDate) }
          : req.query.sortPrice
          ? { price: Number(req.query.sortPrice) }
          : req.query.sortDate
          ? { createdAt: Number(req.query.sortDate) }
          : { createdAt: -1 }
      );

I want to make new field called finalPrice, finalPrice will contain basePrice - discountPrice, and i want to sort finalPrice with .sort() method, or anyone knows the best answer?, my point is make new field finalPrice = basePrice - discountPrice, and i want sort finalPrice

CodePudding user response:

// Find marketItem based on itemTypes
const marketItem = await MarketItem.aggregate([
  req?.query?.itemType
    ? {
        $match: { item: { $in: _ids }, itemType: { $in: itemType } }
      }
    : {
        $match: { item: { $in: _ids } }
      },
  {
    $addFields: {
      finalPrice: { $subtract: ['$price.basePrice', '$price.discountPrice'] }
    }
  }
])
  .sort(
    req.query.sortPrice && req.query.sortDate
      ? { finalPrice: Number(req.query.sortPrice), createdAt: Number(req.query.sortDate) }
      : req.query.sortPrice
      ? { finalPrice: Number(req.query.sortPrice) }
      : req.query.sortDate
      ? { createdAt: Number(req.query.sortDate) }
      : { createdAt: -1 }
  )
  .skip(startIndex)
  .limit(limit)
  .exec();
  • Related