0
私のusersSchema
で、私はhash
フィールドにハッシュパスワードを設定したいと思います。スキーマは次のようになります。マングーススキーマメソッドと "this"更新プロパティ - NodeJS
// models/user-model.js
const usersSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
hash: String,
salt: String
}, { timestamps: true });
usersSchema.methods.setPassword = (password) => {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};
私のルートでは、名前、電子メール、パスワードで新しいユーザーを設定しようとしています。ここでルートがあります:
// routes/users.js
router.get('/setup', (req, res) => {
const user = new User();
user.name = 'Jacob';
user.email = '[email protected]';
user.setPassword('password');
user.save()
.then((user) => {
const token = user.generateJwt();
res.json({ yourToken: token });
})
.catch((err) => {
res.json(err);
});
});
Iルートからconsole.log(user)
、それは私に次を与えた場合: {名:「ヤコブ、電子メール: '[email protected]'}
私がことを知っていますsetPassword
メソッドは、適切なハッシュを作成するまで機能します。ただし、これらのハッシュをuser
オブジェクトに保存することはありません。 を呼び出すuser
オブジェクトに適用して、salt
とhash
のプロパティを設定できるようにするにはどうすればよいですか?
えっ:
は、通常の関数宣言を使用してみてください。確かにそれは分かりませんでした。しかし、確かに、それは働いた!これを読んだ人のために、私はその答え[ここ](https://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/)をもっと読んでいます。 – Jacob