【发布时间】:2021-09-09 11:08:36
【问题描述】:
所以这是我的代码,基本上我想做的就是如果用户想要更改密码,则更改密码,否则它将保持不变。虽然,当我更改它时,它不会被散列,因为它会自动接受来自前端的输入(req.body.password)。看起来最后一个 Promise 并没有等待前一个 Promise 完成并将密码设置为新的。
profileRoutes.put("/profile/:userid", (req, res) => {
const { userid } = req.params;
const { firstName, lastName, email, imageUrl } = req.body;
let password = req.body.password;
let newPassword = null;
// We need a validation here?
User.findById(userid)
.then((user) => {
console.log("user", user);
console.log(user.password === password);
if (user.password !== password) {
console.log("setting the new pass");
const salt = bcrypt.genSaltSync(10);
newPassword = bcrypt.hashSync(password, salt);
console.log("password:", password, "newPassword:", newPassword);
password = newPassword;
}
}).then(User.findByIdAndUpdate(
userid,
{ firstName, lastName, email, imageUrl, password },
{ new: true }
)
.then((response) => {
console.log("response after update", response);
res.status(200).json({ message: `User ${userid} has been updated` });
})
.catch((err) => {
console.log(err);
res
.status(500)
.json({ message: "Something went wrong updating the user" });
})
);
});
这是我在控制台中得到的:
user {
[0] imageUrl: 'http://media.istockphoto.com/vectors/default-profile-picture-avatar-photo-placeholder-vector-illustration-vector-id1223671392?k=6&m=1223671392&s=612x612&w=0&h=NGxdexflb9EyQchqjQP0m6wYucJBYLfu46KCLNMHZYM=',
[0] role: 'USER',
[0] fileUrl: [],
[0] _id: 60d70093e08f660bebec5589,
[0] firstName: 'Tiago',
[0] lastName: 'Pereira',
[0] email: 'tiago@gmail.com',
[0] password: '$2a$10$yExMB9eSs1EyqSbrvE8a1udqOMo09GG.SSyr0BJmZb70mqpcJByiC',
[0] createdAt: 2021-06-26T10:25:23.245Z,
[0] updatedAt: 2021-06-26T10:25:23.245Z,
[0] __v: 0
[0] }
[0] false
[0] setting the new pass
[0] password: qwertyasd newPassword: $2a$10$Xudvsq4CkkDU7bHcQIvH.OyfhlDe1/u3Q1Qv6wmv79f4B5TSFVDi.
[0] response after update {
[0] imageUrl: 'https://res.cloudinary.com/dulzxixhi/image/upload/v1624703139/School%27s%20Cool/wnc8vjpgunrkvolnldb4.jpg',
[0] role: 'USER',
[0] fileUrl: [],
[0] _id: 60d70093e08f660bebec5589,
[0] firstName: 'Tiago',
[0] lastName: 'Pereira',
[0] email: 'tiago@gmail.com',
[0] password: 'qwertyasd',
[0] createdAt: 2021-06-26T10:25:23.245Z,
[0] updatedAt: 2021-06-26T10:26:20.237Z,
[0] __v: 0
[0] }
【问题讨论】:
-
但是它在promise里面,所以它应该把密码设置为新密码,然后findByIdAndUpdate应该启动,对吧?!
标签: node.js mongodb express promise passport.js