Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to save a user to mongodb database using post request as follow, but I got the error bcrypt Error: data and hash arguments required .It's a pretty simple set up of the code but i can't figure out anything wrong with it. models/users.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
required: true
},
username:{
type: String,
required: true
},
password: {
type: String,
required: true
}
});

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id,callback){
User.findById(id,callback);
}

module.exports.getUserByUsername = function(username,callback){
const query = {username:username}
User.findOne(query,callback);
}

module.exports.addUser= function (newUser, callback) {
   bcrypt.genSalt(10,(err,salt) => {
   bcrypt.hash(newUser.password, salt , (err, hash) =>{
        if(err) throw (err);

        newUser.password=hash;
        newUser.save(callback);
   });
   });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

The error comes from the bcrypt.hash method. In your case, you have the following piece of code :

bcrypt.hash(newUser.password, salt , (err, hash) => { ... }

I think that your problem comes from the newUser.password that must be empty (null or undefined). The error says data and salt arguments required. It looks like your salt is correctly generated and you didn't check if newUser.password === undefined, so here's my bet: somehow newUser.password is undefined.

Also, you can check if the genSalt method works fine by adding if(err) throw (err); after calling it as you did for the bcrypt.hash method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...