2016-07-15 4 views
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オブジェクトに適用して、salthashのプロパティを設定できるようにするにはどうすればよいですか?

答えて

2

太い矢印の表記を使用すると、がsetPasswordを参照しているものを変更しているため、ユーザーのドキュメントをもう指していません。

usersSchema.methods.setPassword = function(password) { 
    this.salt = crypto.randomBytes(16).toString('hex'); 
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
}; 
+0

えっ:

は、通常の関数宣言を使用してみてください。確かにそれは分かりませんでした。しかし、確かに、それは働いた!これを読んだ人のために、私はその答え[ここ](https://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/)をもっと読んでいます。 – Jacob

関連する問題