node.js - 使用 Mongoose 保存身份验证凭据时出现问题

标签 node.js mongodb mongoose

我正在用 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);
    })
});

我正在创建模式的新实例,并使用该实例访问实例方法,问题是字段“hash”和“salt' 受实例方法影响,完全不受影响。

我在控制台中打印哈希和盐,它们正在生成但没有保存,事实上,当我检查 Mongo 时,所有内容都被存储但哈希和盐没有。我做错了什么吗?

最佳答案

问题是您的setPasswordvalidPassword 方法是箭头函数。 箭头函数将 this 绑定(bind)到周围范围的上下文。在您的情况下,它将是全局范围。

将您的方法更改为常规函数,它将起作用:

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;
}

关于node.js - 使用 Mongoose 保存身份验证凭据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090976/

相关文章:

node.js - Socket.io:如何正确加入和离开房间

Python "int64"无法转换为 MySQL 类型

mongodb - 使用 pymongo 使用 expireAfterSeconds 创建 mongodb 集合索引

node.js - Mongoose模型架构和Node需要顺序

node.js - Mongoose:需要 .pre Hook 来递归删除树中的子项

node.js - 在 Gruntfile 中使用 JavaScript 库

javascript - 使用 webpack,我可以将 Node.js 和浏览器代码放在同一个文件中,但阻止 Node.js 代码进入浏览器吗?

node.js - Node JS : net. Socket 不是构造函数

Heroku 上的 Node.js Express 应用程序无法使用 Mongoose 连接到 MongoLab 数据库

javascript - 仅当 mongoDB Node JS 上存在集合时才显示给客户端