node.js - 获取 bcrypt 所需的错误数据和盐参数?
问题描述
我正在尝试按如下方式将用户保存到 MongoDB,但我收到错误 bcrypt Error: data and hash arguments required。我检查了 StackOverflow 上其他开发人员提出的相同错误问题,但没有帮助。我附上了模型文件和路由器文件的代码。
- 用户模型文件
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const uSchema = new mongoose.Schema({
fullName: {
type: String,
required: true,
min: 4,
max: 30
},
email: {
type: String,
required: true,
trim: true,
unique: true,
index: true
},
hash_password: {
type: String,
required: true,
min: 6,
max: 12
},
role: {
type: String,
enum: ['user', 'admin', 'moderator'],
default: 'admin'
}
}, { timestamps: true });
uSchema.virtual('password')
.set(function (password) {
this.hash_password = bcrypt.hashSync(password, 10);
});
uSchema.methods = {
authenticate: function (password) {
return bcrypt.compareSync(password, this.hash_password);
}
}
module.exports = mongoose.model('User', uSchema);
- 用户路由器文件
const express = require('express');
const router = express.Router();
const User = require('../models/user.model');
router.post('/login', (req, res) => {
});
router.post('/signin', (req, res) => {
User.findOne({ email: req.body.email })
.exec((error, user) => {
if (user) return res.status(400).json({
message: 'User already exists.'
});
const {
fullName,
email,
password
} = req.body;
const _user = new User({
fullName,
email,
password
});
_user.save((error, data) => {
if (error) {
return res.status(400).json({
message: 'Something went wrong'
});
} if (data) {
return res.status(201).json({
user: data
})
}
})
});
});
module.exports = router;
解决方案
您可以router
改为在文件中执行此操作。
const bcrypt = require("bcrypt")
// ...
router.post('/signin', (req, res) => { // Change this to signup
User.findOne({ email: req.body.email })
.exec((error, user) => {
if (user) return res.status(400).json({
message: 'User already exists.'
});
const {
fullName,
email,
password
} = req.body;
const hashedPassword = bcrypt.hashSync(password, 10);
const _user = new User({
fullName,
email,
hashedPassword
});
_user.save((error, data) => {
if (error) {
return res.status(400).json({
message: 'Something went wrong'
});
} if (data) {
return res.status(201).json({
user: data
})
}
})
});
});
module.exports = router;
virtual
并从模型中删除密码。
推荐阅读
- spring - 在 Spring Data MongoDB 的集合中添加具有默认值的新字段
- android - 卡在 firebase_token.java
- reactjs - 反应在类外引用 const
- verilog - Verilog:如何在case语句中将值范围定义为单个条件?
- jenkins-plugins - 使用 Jenkins 邮件程序 webhook 将 Alertmanager 警报发送到我的电子邮件地址
- c# - 方法上的长数据类型接受一个 int
- javascript - 如何在hammer.js中按类名选择元素?
- agda - Agda 是否支持重命名变量?
- javascript - 如何使用 Angular 7 和 FCM(Firebase 云消息传递)计算后台通知消息
- javascript - 三.js用点做烟雾效果