javascripthashpasswordsbcryptuser-object

Can I create a user object inside password hash function?


I was following a Backend REST Api tutorial, and in the video, this is what he did, creating a user object, then changing newUser.password to the hash generated.

// Data is valid, register user
let newUser = new User({
    name,
    username,
    password,
    email,
});
// Hash password 
bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password, salt, (err, hash) => {
        if (err) throw err;
        newUser.password = hash;
        newUser.save().then(user => {
            return res.status(201).json({
                success: true,
                msg: "User is now registered"
            })
        })
    })
})

Why not just do it all at once?

// Why not do it in one go instaed of creating and then changing User?
bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(password, salt, (err, hash) => {
        if (err) throw err;
        let newUser = new User({
            name,
            username,
            hash,
            email,
        });
        newUser.save().then(user => {
            return res.status(201).json({
                success: true,
                msg: "User is now registered"
            })
        })
    })
})

Is there something wrong with doing it together?


Solution

  • since bcrypt takes a callback function your hash is only gonna be available between the brackets for the callback function, which is why you do the assignment between those brackets. since you declare newuser between those brackets then newuser isn't available in the greater scope