Vivek Aasaithambi
Vivek Aasaithambi

Reputation: 929

Using project fields in calculation on mongoose

.project({
        percentage_amount: {
          $multiply: ["$commission", {
                    $divide: ["$price", 100]
            }]
        },
        payable: {
          $subtract: ["$price", percentage_amount]
        }
    })

Is this possible in mongoose? if not, how to do that? kindly help me out

Upvotes: 1

Views: 442

Answers (1)

chridam
chridam

Reputation: 103445

Yes it's possible with the aggregation framework. You can either use the aggregate() pipeline builder as:

Model.aggregate()
     .project({
          "percentage_amount": {
              "$multiply": [
                   "$commission", {
                       "$divide": ["$price", 100]
                   }
              ]
           },
           "payable": {
               "$subtract": ["$price", percentage_amount]
           }
      })
      .exec(function(err, result) {
          if (err) return handleError(err);
          console.log(result)
      });

or using the aggregate() operator pipeline array:

Model.aggregate([
    {
      "project": {
          "percentage_amount": {
              "$multiply": [
                   "$commission", {
                       "$divide": ["$price", 100]
                   }
              ]
           },
           "payable": {
               "$subtract": ["$price", percentage_amount]
           }
    }
]).exec(function(err, result) {
    if (err) return handleError(err);
    console.log(result)
});

Upvotes: 1

Related Questions