シャシャ:
これは私のユーザモデルであります:
const schema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
min: 6,
max: 255
},
password: {
type: String,
required: true,
max: 1024,
min: 6
}
});
schema.pre("save", async next => {
if (!this.isModified("password")) return next();
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
return next();
} catch (error) {
return next(erro);
}
});
module.exports = mongoose.model("User", schema);
私は、ユーザーを保存するとき、それは空のオブジェクトを返すと、それは保存しないと作業していません。私はすべきでは何をするか分からないのですか?何が問題ですか?
SuleymanSah:
あなたは、ミドルウェアの保存前の内側に矢印機能の代わりに、関数形式を使用する必要があります。アロー機能は、この自分自身を結合しないので。
schema.pre("save", async function(next) {
if (!this.isModified("password")) return next();
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
return next();
} catch (error) {
return next(error);
}
});