how do you add multiple numbers from an object that comes from a database?

code:

  const _id = req.body.idLights;

      Feed.findById(_id, (err, fountItemsFeed) => {
        Feed.findByIdAndUpdate(_id, { lights: fountItemsFeed.lights }, (err, foundItemsLights) => {
          if (err) {
            console.log(err);
          } else {
            foundItemsLights.lights = fountItemsFeed.lights + 1;
            foundItemsLights.save();  
          }
        });

        User.findByIdAndUpdate(
          req.user.id,
          { lights: fountItemsFeed.lights },
          (err, foundItemsLights_Stats) => {
            Feed.find({id: fountItemsFeed.id}, (err, result) => {
              result.forEach((feed) => {
                console.log(feed)
          })
          // foundItemsLights_Stats.save();
            });
            res.redirect("/#" + _id);
          }
        );
      });
}); 

code from DB: in console

{
 _id: 612bfc5846f57f411406a024,
 comm: [],
 id: '6128b92bd5a7192e30100110',
 profile_name: 'Iuliaan ๐ŸŽ‰๐Ÿงจ' ,
 lights: 28,
 __v: 0
}
{
 _id: 612bfc9a46f57f411406a03d,
 comm: [],
 id: '6128b92bd5a7192e30100110',
 profile_name: 'Iuliaan ๐ŸŽ‰๐Ÿงจ' ,
 lights: 8,
 __v: 0
}
{
 _id: 612bfcce46f57f411406a048,
 comm: [],
 id: '6128b92bd5a7192e30100110',
 profile_name: 'Iuliaan ๐ŸŽ‰๐Ÿงจ' ,
 lights: 14,
 __v: 0
}

and i put instead console.log(feed) i put (feed.lights) i see in console:

28
8
14

how add all numbers dynamics? i want all numbers add ” 28 + 8 + 14 = 50 ” how can i do in javascript to gather all those numbers dynamically? I need a quick fix. Thank you very much!

Answer

You could use a reducer on your array in this way:

let result = [{
 _id: "612bfc5846f57f411406a024",
 comm: [],
 id: '6128b92bd5a7192e30100110',
 profile_name: 'Iuliaan ๐ŸŽ‰๐Ÿงจ' ,
 lights: 28,
 __v: 0
},
{
 _id: "612bfc9a46f57f411406a03d",
 comm: [],
 id: '6128b92bd5a7192e30100110',
 profile_name: 'Iuliaan ๐ŸŽ‰๐Ÿงจ' ,
 lights: 8,
 __v: 0
},
{
 _id: "612bfcce46f57f411406a048",
 comm: [],
 id: '6128b92bd5a7192e30100110',
 profile_name: 'Iuliaan ๐ŸŽ‰๐Ÿงจ' ,
 lights: 14,
 __v: 0
}];

const reducer = (accumulator, currentValue) => accumulator + currentValue.lights;

console.log(result.reduce(reducer, 0));