【发布时间】:2020-03-17 15:06:22
【问题描述】:
我正在尝试构建一个需要用户注册和登录功能的简单应用程序。我已将用户架构定义如下:
// User Schema
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
trim: true,
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
name: {
// TODO : Add validation for name
type: String,
required: true
},
mobile:{
// TODO : Add validation for mobile numbers
type: String
}
}, {
timestamps: true
});
userSchema.pre('save', async function (next) {
const user = this
console.log("inside pre")
if (user.isModified('password')) {
console.log("about to hash ", user.password )
user.password = await bcrypt.hash(user.password, 8)
console.log("hashed pwd ", user.password )
}
next();
})
在我的路线中,我有以下内容:
router.post('/users', async (req, res) => {
const user = new User(req.body)
try {
console.log("about to save ")
await user.save()
console.log("About to gen token")
const token = await user.generateAuthToken()
console.log("About to send res")
res.status(201).send({ user, token })
} catch (e) {
res.status(400).send(e)
}
})
原始密码和明文都会打印,但从不发送响应。保存函数调用之后的行永远不会被执行。为什么会发生这种情况?
【问题讨论】: