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
});
}
});
})
});