I created an simple CRUD operation in nodejs and mongoose. Updating an user using RESTAPI. an error message in Insomnia
Error: Server returned nothing (no headers, no data)
URL
http://localhost:1337/api/users/update/63ab9b716065482273e58b75
@PUT METHOD
router.put("/update/:id",updateUser)
const updateUser = async (req,res,next) => {
if (req.params.id === req.user.id) {
try {
const updateuser = await User.findByIdAndUpdate(req.params.id, {
$set:req.body,
})
res.status(200).json(updateuser)
} catch (error) {
next(error)
}
}
}
how to updating with id of user
CodePudding user response:
req.params.id
will be of type string, while req.user.id
will be probably of type ObjectId.
Can you try this:
if (req.params.id.toString() === req.user.id.toString()) {
CodePudding user response:
As mentioned before req.user.id type is ObjectId. Also you should send an error when ids are not the same.
Example for your code:
const updateUser = async (req, res, next) => {
try {
if (req.params.id !== req.user.id.toString()) {
// Send error in here.
}
const updateuser = await User.findByIdAndUpdate(req.params.id, {
$set: req.body,
});
res.status(200).json(updateuser);
} catch (error) {
next(error);
}
};