Friday, 8 May 2020

How to check if request body contains a field when updating a document?

I have this piece of code:// Update a card router.patch('/:id', async (req, res) => { try { const card = await Card.findByIdAndUpdate( {_id: req.params.id}, { $set: { title: req.body.title, description: req.body.description}}, { new: true }); res.json(card); } catch (error) { res.status(404).json({message: error}); } }); I want to be able to update the title and the description individually, meaning if I send a JSON containing only the title, then only the title will be updated, the problem is that if I do this with the code above, because description is missing then description will be updated to null. Is there a way to update only what I send in the JSON?

Submitted May 08, 2020 at 11:56PM by Dafuq313

No comments:

Post a Comment