Shreyans Patel
Shreyans Patel

Reputation: 51

Trying to store hashed username in database

I am trying to hash the username using the JavaScript-MD5 plugin, and then store it to the database to use with Jdenticon. I am able to hash the password and log it to the console using var hash = md5($scope.username); but am unable to pass it to my newUser variable.

  1. Registration Controller

    $scope.register = function(){
    var hash = md5($scope.username);
    console.log(hash);
    var newUser = {
      email: $scope.email,
      password: $scope.password,
      username: $scope.username,
      userHash: hash
    };
    
    $http.post('/users/register', newUser).then(function(){
      $scope.email = '';
      $scope.password = '';
      $scope.username = '';
      userHash = '';
    };
    
  2. Registration Route:

    app.post('/users/register', function(req, res) {
    
      bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(req.body.password, salt, function(err, hash) {
          var user = new User({
            email: req.body.email,
            password: hash,
            username: req.body.username,
            userHash: req.body.userHash
          });
          console.log(user);
    
          user.save(function(err) {
             if (err) return res.send(err);
    
             return res.send();
          });
        });
      });
    });
    

Upvotes: 1

Views: 130

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

I guess you may missed userHash property in your User model that's why you can't store userHash in your database.

So you should include first userHash in your User model then should be working fine.

like:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var UserSchema= new Schema({
    username : {
        type: String,
        required: true
    },
    email: {
        type: String
    },
    password: {
        type: String
    },
    userHash:{
        type: String
    }
});
mongoose.model('User', UserSchema);

Upvotes: 1

Related Questions