使用Mongoose保存身份validation凭据的问题

我正在用Express和Mongo制作一个简单的Node.js API,我将在后期使用React制作一个前端,但是现在我只是添加了模型,并且遇到了问题模型)密码没有被存储。

这是我的代码:

const mongoose = require('mongoose'); const crypto = require('crypto'); const UserSchema = new mongoose.Schema({ name: {type: String, required: true}, username: {type: String, required: true}, email: {type: String, required: true, lowercase: true, index: true}, hash: String, salt: String }); UserSchema.methods.setPassword = (password) => { this.salt = crypto.randomBytes(16).toString('hex'); this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex'); }; UserSchema.methods.validPassword = (password) => { let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex'); return this.hash === hash; } mongoose.model('User', UserSchema); module.exports = mongoose.model('User'); 

我有两个在我的模式中定义的实例方法,我只能访问该模式的一个实例,我试图在这里做:

 const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const UserSchema = require('./User'); router.use(bodyParser.urlencoded({extended: true})); router.post('/users', (req, res) => { let body = req.body; const User = new UserSchema(); User.name = body.name; User.username = body.username; User.email = body.email; User.setPassword(body.password); User.save((err, user) => { if (err) return res.status(500).send('There were problems while creating the user.'); res.status(200).send(user); }) }); 

我正在创build一个新的模式实例,并且访问实例方法,问题是实例方法影响的字段' hash '和' salt '似乎根本没有受到影响。

我在控制台打印散列和盐,他们正在生成,但没有保存,事实上,当我检查Mongo的一切都被存储,但哈希和盐不是。 难道我做错了什么?

问题是你的setPasswordvalidPassword方法是箭头函数。 箭头函数将其绑定到周围范围的上下文。 在你的情况下,这将是全球范围。

改变你的方法到正常的function,它将工作:

 UserSchema.methods.setPassword = function(password) { this.salt = crypto.randomBytes(16).toString('hex'); this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex'); }; UserSchema.methods.validPassword = (password) { let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex'); return this.hash === hash; }