Updating array of objects in mongoose based off key in objects value
you want to using $push
and $set
in one findByIdAndUpdate, that's impossible, I prefer use findById()
and process
and save()
so just try
exports.makePicks = async (req, res, next) => { const picks = req.body; try { //implementation business logic let result = await User.findById(req.user._id) if(result.picks && result.picks.length > 0){ result.picks.forEach(item =>{ if([`week-${req.params.week}`] in item){ item[`week-${req.params.week}`] = picks } else{ result.picks.push({ [`week-${req.params.week}`] : picks }) } }) } else{ result.picks.push({ [`week-${req.params.week}`] : picks }) } await result.save() res.redirect('/api/dashboard'); } catch (error) { console.log(error) }}
note: don't use callback
and async/await
together
exports.makePicks = async (req, res, next) => { const picks = req.body; const { week } = req.params; try { let result = await User.findById(req.user._id); const data = { [`week-${week}`]: picks }; const allPicks = [...result.picks]; if (allPicks.length > 0) { // Search index of peek const pickIndex = _.findIndex(allPicks, (pick) => { return Object.keys(pick)[0] == `week-${week}`; }); // If found, update it if (pickIndex !== -1) { console.log(chalk.green("true")); allPicks[pickIndex] = data; } // Otherwise, push new pick else { console.log(chalk.red("false")); allPicks.push(data); } } else { allPicks.push(data); console.log(chalk.yellow('results.picks is empty')) } result.picks = allPicks; console.log('allPicks', allPicks); await result.save(); res.redirect("/api/dashboard"); } catch (error) { console.log(error); }};