Monday 27 April 2020

Updating single fields in an entry using express router

Hello all. Creating my first app with MERN, I'm trying to establish endpoints for CRUD ops. The tutorial I was following used express router for get and post requests to a mongodb, but the tutorial was sending every field an entry needs for a collection.I am just wanting to update a single field in an entry instead of having to send all the extra information again.right now I have a route that I only want to toggle an active or deactive flag for the userRoutes.route('/user/:id/deactivate').put(function(req, res) { USER.findById(req.params.id, function(err, user) { if(!user) { res.status(404).send("data is not found"); } else { user.user_active = req.body.user_active; user.save().then(user => { res.json('User updated successfully!'); }) .catch(err => { res.status(400).send("Update not possible"); }); } }); }); the model for the user is{ "user_name": "T. Elliot Sanders", "user_address": "100 west rd", "user_phone": "123456789", "user_cart": { "items": [], "total": 0, "formattedTotal": "0" }, "user_active": true } but when I run the route using postman to only update the user_active flag to false the entry in the collection has everything deleted except the user_active field. so after the route the entry is{ "user_active": false } So how do I update the single field, but not delete the others, but also not have to resend information that has not changed?

Submitted April 27, 2020 at 09:38PM by notalentnodirection

No comments:

Post a Comment