【发布时间】:2021-12-24 07:45:39
【问题描述】:
bcryptjs 版本:"bcryptjs": "^2.4.3"
猫鼬版:"mongoose": "^6.0.12"
我正在尝试在用户创建或密码更新时加密用户密码。当我使用User.create() 创建单个用户时,一切都按预期工作(密码已加密)。当我使用User.insertMany() 时,数据插入成功,但密码未加密。这是我的架构:
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
voterId: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
unique: true,
},
votedFor: [
{
type: mongoose.Schema.ObjectId,
ref: 'Election'
}
],
finishedVoting: {
type: Boolean,
required: true,
default: false
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
},
{
timestamps: true,
}
)
userSchema.pre('save', async function(next) {
// Only run this function if password was actually modified
if (!this.isModified('password')) return next();
// Hash the password with salt 10
this.password = await bcrypt.hash(this.password, 10);
next();
});
这是我尝试插入的一些示例数据:
const voters = [
{
name: "Sherali",
surname: "Samandarov",
voterId: "194199",
password: "FA654644", //will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
},
{
name: "Sherali",
surname: "Samandarov",
voterId: "184183",
password: "MB454644", //will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
},
{
name: "Sherali",
surname: "Samandarov",
voterId: "194324",
password: "FA651684", //will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
}
]
我猜userSchema.pre('save', ...) 出于某种原因不会在insertMany() 上触发
【问题讨论】:
标签: javascript mongodb mongoose bcryptjs