I have a MongoDB schema that I have some time a single array and sometimes I have more than 20 arrays values in it, each array has a field value which I want to sum together and insert the sum into another field in my MongoDB. Here is what am trying to say, here is my schema, How can i add the value of weight together for every package array inserted to the schema and let it be my total weight schema
{
"status": "In warehouse",
"paymentStatus": "incomplete",
"_id": "5d8b56476a3e4ae2d01f2953",
"unitNo": "0002",
"warehouseNo": "0001",
"trackingNo": "FPZ848505936",
"packages": [
{
"date": "2019-09-26T06:30:39.561Z",
"_id": "5d8c5b0f756838f78d5205d7",
"category": "chil",
"quantity": "177",
"description": "a valueablegoods",
"width": 15,
"itemweight": 123,
"length": 17,
"height": 21,
"dimension": 31.25903614457831,
"weight": 32.25903614457831
},
{
"date": "2019-09-26T06:30:39.561Z",
"_id": "5d8c5b0f756838f78d5202dd,
"category": "chil",
"quantity": "177",
"description": "a valueablegoods",
"width": 15,
"itemweight": 123,
"length": 17,
"height": 21,
"dimension": 35.25903614457831,
"weight": 30
},
{
"date": "2019-09-26T06:30:39.561Z",
"_id": "5d8c5b0f756838f78d51aeq",
"category": "chil",
"quantity": "177",
"description": "a valueablegoods",
"width": 15,
"itemweight": 123,
"length": 17,
"height": 21,
"dimension": 32.25903614457831,
"weight": 44
}
],
"totalWeigth": "This should add all weight value in my packages array together and if it is only 1 it should brings only the one"
"date": "2019-09-25T11:57:59.359Z",
"__v": 0
}
This is the api route that add the packages to the package array field and i want the totalWeight to be update anytime new packge is add or updated
// @route POST api/admins/addshipment/:unitNo
// @desc Add shipment for each customer
// @access Private
router.post(
'/addshipment/:unitNo',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Shipments.findOne({unitNo: req.params.unitNo}, {paymentStatus: "incomplete"})
.then(shipments => {
if(shipments === null || shipments.paymentStatus === "complete"){
const errwarehouse = "This user doesn't have an existing warehouse";
return res.status(404).json(errwarehouse);
}else{
if (shipments.paymentStatus === "incomplete") {
function getPrice(){
if (initial > dimension){
return initial
}else if(initial === dimension) {
return initial
}else{
return dimension
}
}
const newPackages = {
category: req.body.category,
quantity: req.body.quantity,
description: req.body.description,
width: req.body.width,
itemweight: req.body.itemweight,
length: req.body.length,
height: req.body.height,
dimension,
weight: getPrice(),
};
Shipments.findOneAndUpdate({unitNo: req.params.unitNo ,paymentStatus: "incomplete"},
{"$push": {"packages": newPackages}}, {totalWeight: {"$sum" : {"packages.weight"}}}) //Here is were i add the package to the package array and here is where i tried sumup packages.weight for every time i add new package
.then(shipments=> res.json(shipments))
}
}
});
});
Thank you