'Update is not woking in node js for postman
router.put("/update/:username", update);
function update(req, res, next) {
userService
.update(req.params.username, req.body)
.then(() => res.json({}))
.catch((err) => next(err));
}
async function update(username, userParam) {
const user = await User.findById(username);
if (!user) throw "User not found";
Object.assign(user, { status: userParam.status });
if (await user.save()) {
throw 'Username "' + user.username + '" is updated';
}
}
Solution 1:[1]
You are using findById but passing the username. You should use findOne instead.
Try to simplify your code like this:
router.put("/update/:username", update);
async function update(req, res, next) {
try {
const user = await User.findOne({ username: req.params.username });
if (!user) return res.status(400).send('User not found');
user.status = req.body.status
await user.save()
res.status(201).send('User updated')
} catch (err) {
next(err)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lpizzinidev |
