0

I am returning an array of document objects from a Mongoose query. The array is populated with expected results.

[{
    _id: 1,
    name: 'Mayonnaise'
},
{
    _id: 2,
    name: 'Gravy'
}]

I am trying to add a new property on to certain objects only where a criteria is met. I've tested this element and the conditional logic is also performing as expected. I loop through the array above and another, larger array to find matching ids. When a match is found, I need to add a property, for example:

{isArchived: true}

to the object in the array returned by the find() query. So I should end up with:

[{
    _id: 1,
    name: 'Mayonnaise'
},
{
    _id: 2,
    name: 'Gravy',
    isArchived: true
}]

The problem is that no matter what I try I cannot get the new property added onto the specific object within the array.

I have tried just about every 'Add property to an object' answer on here, so am just about ready to start throwing things!!

Thanks for any and all help!

EDIT: The entire router code is as follows:

router.get('/edit/:id', ensureAuthenticated, (req, res) => {
  Menu.findOne({ _id: req.params.id })
  .populate('recipes')
  .then(menu => {
    Recipe.find({user: req.user.id}, function (err, allRecipes) {
      if(menu.user != req.user.id){
        req.flash('error_msg', 'Not Authorised!');
        res.redirect('/menus');
      } else {  
        //use momentjs to format dates to YYYY-MM-DD
        const vFromDate = moment(menu.validFrom).format('YYYY-DD-MM');
        const vToDate = moment(menu.validTo).format('YYYY-DD-MM');

        const selectedRecipeIds = menu.recipes.map(id => id._id);

        for (var i = 0; i < allRecipes.length; i++){
          for (var j = 0; j < selectedRecipeIds.length; j++){
            if (JSON.stringify(allRecipes[i]._id) == JSON.stringify(selectedRecipeIds[j]._id)) {
              allRecipes[i].isSelected = true
            }
          }
        }

        res.render('menus/edit', {
          menu,
          vFromDate,
          vToDate,
          allRecipes
        });
      }
    });
  })
});
user22927
  • 13
  • 1
  • 4

2 Answers2

0
a = [{
    _id: 1,
    name: 'Mayonnaise'
},
{
    _id: 2,
    name: 'Gravy'
}]

a[0].isArchived = true

mat's
  • 49
  • 1
  • 10
  • Thanks @mat's for the response, but no joy I'm afraid. When I console.log the entire array it is resolutely unchanged! – user22927 Dec 14 '18 at 21:54
0

I think you are trying to mutate the original objects that came from the response. Try to operate on a copy, like this:

const allRecipiesCopy = [...allRecipies]

And then loop over this array, and mutate these objects, not original ones.

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18