Reputation: 45
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."})
}
})
}
}
Upvotes: 0
Views: 608
Reputation: 3496
findOneAndUpdate
cannot do what you are looking for alone. It only finds a record and updates it immediately - you cannot do any sort of check as to the record's current contents.
You need to do something along the lines of a findOne
to retrieve the current user record, check to see if the password from the DB matches the new one, and then use findOneAndUpdate
to update the password if it matches your criteria.
Also, allow me to add an obligatory reminder never to store your users' passwords plaintext in the database. You should look up password hashing best practices and implement those, but that's out of scope for this question/answer.
Upvotes: 1