Error in updating form values in mongoDB using nodejs
You need to read from your req.body, and use those values to create employee body.
router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) { return res.status(400).send(`Not a valid id ${req.params.id}`); } const { email, name, position, office, salary } = req.body; var emp = { email, name, position, office, salary }; Employee.findByIdAndUpdate( req.params.id, { $set: emp }, { new: true }, (err, doc) => { if (!err) { if (doc) { res.send(doc); } else { res.status(400).send("Not found"); } } else { console.log(err); res.status(500).send("Something went wrong"); } } );});
Let's say you have this employee document.
{ "_id" : ObjectId("5e01d6d21151ad62600b1ba6"), "name" : "Employee 1", "position" : "Web developer", "office" : "Software", "salary" : 1111, "email" : "emp1@microsoft.com", "__v" : 0}
If we want to update position and salary, we can use this request.body:
{ "name": "Employee 1", "position": "Senior Web developer", "office": "Software", "salary": 2222, "email": "emp1@microsoft.com"}
When you send a PUT request to your route (.../5e01d6d21151ad62600b1ba6
) with this body, the result will be like this:
{ "_id": "5e01d6d21151ad62600b1ba6", "name": "Employee 1", "position": "Senior Web developer", "office": "Software", "salary": 2222, "email": "emp1@microsoft.com", "__v": 0}