Luis Gonzalez
Luis Gonzalez

Reputation: 111

Sum an specific field from all elements mongoose

I have a collections in mongoose that store each order line, with price, product name, quantity, and total price from multiplying price with quantity, , what I am trying TO achieve is insert in ejs the total amount of the order with the sum of total price from each element or line, basically sum all elements total field and inserted in ejs.

I took a look to the mongoose and mongodb documentation I found the $sum element but it did not answer my question.

 WE CAN SEE THE ELEMENT.

{ _id: 5d58512fe1ec313138b426d5,
  amount: 12,
  name: 'Bisagras de 3/8',
  price: 2.15,
  total: 25.799999999999997 }

 BELOW IS THE GET REQUEST IN NODE JS

 app.get("/order", function(req, res) {

    Order.find({}, function(err, data) {
       res.render("order", {ordenItem: data});  
    });
 });

AND THIS IS THE EJS PAGE

<% ordenItem.forEach(function(item){ %>

    <form action="/delete"  method="post" class="order">
        <div class="item">
            <input id="checkbox" type="checkbox" name="checkbox" value=" 
            <%= item._id %>" onChange="this.form.submit()">
            <h3><%=   item.amount  %> <%= item.name %> <%=  item.price %> 
            </h3>
        </div>

     <h3 class="price"><%= item.total++  %></h3>
   </form>

Upvotes: 0

Views: 713

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

You can actually do this, to get the total amount for orders, this does sum up total across all the lines :

Order.aggregate({
    $group: {
        _id: '',
        totalAmount: { $sum: '$total' }
    }
 }, {
    $project: {
        _id: 0
    }
})

Upvotes: 1

Related Questions