0

this is my user schema

 let mongoose = require('mongoose');
mongoose.set('debug', true);

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

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

and this is the user route file where am trying to insert a new user

if(errors){
            res.render('register',{
                errors:errors
            })
        }else{
            bcrypt.genSalt(10,(err,salt)=>{
                bcrypt.hash(password,salt,(err,hash)=>{
                    if(err){
                        console.log("hash did not work");
                    }

                        newUser.password = hash;
                        console.log(newUser.password);


                });
            })
            than()
            var newUser =  new User({
                name:name,
                email:email,
                username:username,
                password:password
            }); 


            console.log(newUser);
                newUser.save((err)=>{
                if(err){
                    console.log(err)
                    return;
                }else{
                    req.flash('success','your now registered and can login');
                    res.redirect('./login');
                }

            });
        }

i tried also assining it dirctly to the new user than save

  newUser.password = hash;

the password is getting hashed when i console log it but it doesnt store as hash value in the new user for example example from db

1
  • The problem is that newUser.password doesn't save the hashed password after asigning? Commented Jan 20, 2019 at 8:20

1 Answer 1

2

You should move newUser.save into bcrypt.hash

if(errors){
    res.render('register',{
        errors:errors
    })
}else{
    bcrypt.genSalt(10,(err,salt)=>{
        bcrypt.hash(password,salt,(err,hash)=>{
            if(err){
                console.log("hash did not work");
            }

            var newUser =  new User({
                name: name,
                email: email,
                username: username,
                password: hash
            }); 

            console.log(newUser);
            newUser.save((err)=>{
                if(err){
                    console.log(err)
                    return;
                }else{
                    req.flash('success','your now registered and can login');
                    res.redirect('./login');
                }

            });

        });
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.