下面是使用bcrypt和Mongoose更改用户密码的示例代码:
首先,安装bcrypt和Mongoose:
npm install bcrypt mongoose
然后,创建一个名为user.js的Mongoose用户模型文件:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
// 使用bcrypt进行密码哈希化
UserSchema.pre('save', async function(next) {
const user = this;
if (user.isModified('password') || user.isNew) {
try {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
next();
} catch (err) {
return next(err);
}
} else {
return next();
}
});
// 比较密码
UserSchema.methods.comparePassword = function(password) {
return bcrypt.compare(password, this.password);
};
module.exports = mongoose.model('User', UserSchema);
在你的应用程序中,你可以使用以下代码更改用户密码:
const User = require('./user'); // 替换为你的用户模型路径
// 更改密码
const changePassword = async (userId, newPassword) => {
try {
const user = await User.findById(userId);
if (!user) {
throw new Error('User not found');
}
user.password = newPassword;
await user.save();
console.log('Password changed successfully');
} catch (err) {
console.error(err);
}
};
// 使用示例
changePassword('userId', 'newPassword');
在这个示例中,我们首先通过用户ID查找用户。然后,我们将用户的password
属性设置为新密码,并通过调用save
方法进行保存。bcrypt中的pre中间件将自动对新密码进行哈希处理。
请记住,与数据库操作相关的代码可能会有所不同,具体取决于你的应用程序结构和架构。以上代码只是一个示例,你可能需要根据你的实际需求进行适当的修改。