[英]Unable to store bcrypt hashed password from JSON into mongodb using mongoose
我無法使用貓鼬將bcrypt哈希密碼從JSON存儲到mongodb中。 我認為setPassword模式方法的實現存在錯誤。 我已將“ bcrypt”替換為“ crypto”實現,並且運行良好。 哈希字符串存儲在數據庫中。 但是用“ bcrypt”無法做到
我的model.js實現
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
// User Schema
const userSchema = new Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
}
});
userSchema.methods.setPassword = function(password) {
const saltRounds = 10;
bcrypt.hash(password, saltRounds, function(err, hash) {
this.password = hash;
});
};
mongoose.model('User', userSchema);
我的路由器控制器實現
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');
const register = (req, res) => {
const newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.username = req.body.username;
newUser.setPassword(req.body.password);
newUser.save((err) => {
// Validations error
if (err) {
res.status(400).json(err);
return;
}
res.status(200).json({
success: true,
message: 'Registration Successful'
});
});
};
this
指向bcrypt.hash
而不是userSchema對象。
userSchema.methods.setPassword = function(password) {
const saltRounds = 10;
var that = this;
bcrypt.hash(password, saltRounds, function(err, hash) {
that.password = hash;
});
};
更新:使用回調或promise
userSchema.methods.setPassword = function(password, cb) {
const saltRounds = 10;
var that = this;
bcrypt.hash(password, saltRounds, function(err, hash) {
that.password = hash;
cb();
});
};
newUser.setPassword(req.body.password, function(){
//Rest of code
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.