Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda