Home > Net >  How to add an extra attribute for %discount when getting products? In MongoDB, NodeJs, Mongoose
How to add an extra attribute for %discount when getting products? In MongoDB, NodeJs, Mongoose

Time:08-24

I am new to NodeJs, Mongoose, MongoDB.

I have this collection of products:

[
  {
    "_id": ObjectId("6300db81604458b99283a79b"),
    "name": "Product",
    "mrp": "200",
    "yourPrice": 152,
    "fromVendor": "62f156491b7a7c055f7c580e",
    "stock": 99,
    "sku": "KT86T2F2V5",
    "totalSold": 1,
    "status": "active",
    "images": [],
    "createdAt": ISODate("2022-08-20T13:02:57.013Z"),
    "updatedAt": ISODate("2022-08-20T13:02:57.013Z"),
    "__v": 0
  },
  {
    "_id": ObjectId("6300dbb7604458b99283a79d"),
    "name": "Product1",
    "mrp": "2000",
    "yourPrice": 1500,
    "fromVendor": "62f156491b7a7c055f7c580e",
    "stock": 4,
    "sku": "XXSNRDI48V",
    "totalSold": 0,
    "status": "draft",
    "images": [],
    "createdAt": ISODate("2022-08-20T13:03:51.212Z"),
    "updatedAt": ISODate("2022-08-20T13:03:51.212Z"),
    "__v": 0
  }
]

So for this collection, I need to find the products whose stock is greater than 0, and whose status is active. After finding those products I need to add an attribute as discount where it will calculate the discount with respect to the mrp(Market price or the Maximum retail price) attribute and yourPrice(A price at which the vendor is selling the product) attribute.

Thank You.

CodePudding user response:

Here's a quick example of how to achieve this with the aggregation pipeline and some standard operators: ( I assumed "discount" is the difference between those 2 fields )

I will mention that there are edge cases to consider, for example can "yourPrice" be higher than "mrp"? if so what is the behaviour you want there? currently it will show a negative discount.

db.collection.aggregate([
  {
    $match: {
      status: "active",
      stock: {
        $gt: 0
      },
      
    }
  },
  {
    $addFields: {
      discount: {
        "$multiply": [
          {
            $divide: [
              {
                $subtract: [
                  {
                    $toInt: "$mrp"
                  },
                  "$yourPrice"
                ]
              },
              {
                $toInt: "$mrp"
              }
            ]
          },
          100
        ]
      }
    }
  }
])

Mongo Playground

  • Related