我回顾了有关此问题的许多讨论,但似乎没有一个对我有帮助。
我使用 mongoose 5.5 来保存用户数据,如下所示:
我的架构如下所示:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");
const userSchema = Schema({
userName: {
type: String
},
firstName: {
type: String
},
surName: {
type: String
},
password: {
type: String,
required: true
}
});
userSchema.pre('save', async function(next){
try {
if(!this.isModified('password')){
return next();
}
const hashed = await bcrypt.hash(this.password, 10);
this.password = hashed;
} catch (err) {
return next(err);
}
});
module.exports = user;
Run Code Online (Sandbox Code Playgroud)
我的注册码如下所示:
exports.register = async (req, res, …Run Code Online (Sandbox Code Playgroud)