Reputation: 88
Post Delete options are working fine but the put is not working it updates successfully but with function String() { [native code] } values.
controller.ts
router.put('/:id', (req,res)=> {
if (!ObjectId.isValid(req.params.id)) {
return res.status(400).send('No record with the given Id ${req.params.id}');
}
var emp = {
email: String,
name : String ,
position : String ,
office : String,
// salary : Number
};
Employee.findByIdAndUpdate(req.params.id, { $set : emp },(err,docs) => {
if (!err) {
res.send(docs);
} else {
console.log('Error in Updating the Employee details' + JSON.stringify(err,undefined,2))
}
});
});
model.ts
const mongoose = require('mongoose');
var Employee = mongoose.model('Employee',{
name : String ,
position : String ,
office : String,
salary : Number,
email : String,
})
module.exports = { Employee }
Upvotes: 1
Views: 73
Reputation: 17858
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" : "[email protected]",
"__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": "[email protected]"
}
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": "[email protected]",
"__v": 0
}
Upvotes: 1