'how to update user profile using nodejs and mongoose
On the client side the user can update their profile through a form where the data is sent via form to the nodejs express backend. I want to use mongoose to update the user info. Here is what I have so far:
app.get("/api/users/:id", authJwt.verifyToken, function(req, res, next) {
User.findOneById(req.userId)({
userId: req.body.userId
}).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (user) {
res.status(400).send({ message: "not user found" });
return;
}
next();
});
Solution 1:[1]
Here is my code and i'm going to change (nom,prenom,email,password,phone,categorieClient) :
const bcrypt = require("bcrypt")
// Update a user identified by the userId in the request
exports.update = (req, res) => {
// Validate Request
if(!req.body.nom) {
return res.status(400).send({
message: "user content can not be empty"
});
}
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password , salt);
console.log(hash)
// Find user and update it with the request body
User.findByIdAndUpdate(req.params.userId, {
nom : req.body.nom || "Untitled user ",
prenom : req.body.prenom ,
email :req.body.email ,
password : hash ,
phone :req.body.phone ,
categorieclient :req.body.categorieclient
}, {new: true})
.then(note => {
if(!note) {
return res.status(404).send({
message: "user not found with id " + req.params.userId
});
}
res.send(note);
}).catch(err => {
if(err.kind === 'ObjectId') {
return res.status(404).send({
message: "user not found with id " + req.params.userId
});
}
return res.status(500).send({
message: "Error updating user with id " + req.params.userId
});
});
};
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 | Achref Tirari |