Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!