Tuesday 28 May 2019

Deleting key-value pair from an object in Express PUT route

Hello everyone,​So I have the following Express PUT route to save some data to the database:router.put( '/:id', (req, res) => { Task.findByIdAndUpdate(req.params.id, req.body.task, (err, updatedTask) => { if (err) { req.flash('error', 'Task not found'); res.redirect('/tasks'); console.log(err); } else { if (req.body.task.enrolledStaff) req.flash('success', 'Task updated'); res.redirect('/tasks'); } else { delete updatedTask.enrolledStaff; updatedTask.save(); } } }); } ) The condition is that if the request body doesn't contain enrolledStaff key, then delete this value from the db collection. The delete operator doesn't seem to work, however if I set the length of the enrolledStaff array to 0 – it works just fine (but this is not what I want to do).What am I doing wrong here?

Submitted May 28, 2019 at 09:34AM by marcusique

No comments:

Post a Comment