I'm new with Node.js, I'm trying to update the profile page, so that a user can input the old pass and the new pass, and that updates in DB
I'm using findOneAndUpdate
and trying to come up with a way to:
1 find the user
2 get the user pass
3 compare the old pass with the pass in DB
4 hash the new pass
5 update user
I can't think of a way to do this with findOneAndUpdate
any idea?
exports.updateUser = (req, res) => {
const {id, username, email, oldPassword, newPassword} = req.body
const v = new Validator()
const schema = {
username: { type: "string" },
email: { type: "email" },
}
const errors = v.validate({ username, email }, schema)
if (errors.length) {
return res.status(400).json({ errors })
}
if (!oldPassword && !newPassword) {
const filter = { _id: id }
const update = { username, email}
userModel.findOneAndUpdate(filter, update, {new: true})
.then( user => {
if (user) {
res.json({message: "User is updated."})
} else {
res.status(400).json({error: "Failed to update user."})
}
})
} else if (oldPassword && newPassword) { // this is the part I can't make
const filter = { _id: id }
const update = { username, email, oldPassword, newPassword}
userModel.findOneAndUpdate(filter, update, {new: true})
// here I need to check if the old pass is good first, then update it with the new hashed pass
.then( user => {
if (user) {
res.json({message: "User is updated."})
} else {
res.status(400).json({error: "Failed to update user."})
}
})
}
}