我正試圖將一個用戶保存到MongoDB,如下所示,但我得到的錯誤是bcrypt Error: data and hash arguments required. 我檢查了StackOverflow上其他Dev提出的同樣的錯誤問題,但沒有任何幫助。我附上了模型檔案和路由器檔案的代碼。
- 用戶模型檔案 。
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, 最大:
},
角色: {
type: String,
enum: ['user', 'admin', 'moderator']。
default: 'admin'/span>
}
}, { 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) 。
- 用戶Router檔案
const express = require('express')。
const router = express.Router()。
const User = require(' ./models/user.model')。
router.post('/login', (req, res) => /span> {
});
router.post('/signin', (req, res) => {
User.findOne({ email: req.body.email })
.exec((error, user) =>/span> {
if (user) return res.status(400).json( {
message: 'User already exists.')
});
const {
全名。
電子郵件。
密碼
} = req.body;
const _user = new User({
全名。
電子郵件。
密碼
});
_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;
uj5u.com熱心網友回復:
你可以在router檔案中代替它。
const bcrypt = require("bcrypt"/span>)
/ ...
router.post('/signin', (req, res) => { // 更改為 signup
User.findOne({ email: req.body.email })
.exec((error, user) =>/span> {
if (user) return res.status(400).json( {
message: 'User already exists.')
});
const {
全名。
電子郵件。
密碼
} = req.body;
const hashedPassword = bcrypt.hashSync(password, 10)。
const _user = new User({
全名。
電子郵件。
哈希密碼
});
_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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324681.html
標籤:
