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

298
Visualizações
Mongoose: Understanding Callbacks vs Async/Await

I am trying to understand a callbacks in mongoose. I really just want to clarify my understanding so I can be sure I am on the right track.

I understanding using async/await to do queries in mongodb using mongoose. For example, the following code will get a user from my database, assuming my model "User" is set up correctly.

const getUser = async () => {
     const user = await User.find({username: "John"})
     return user
}

Here is my problem. I am working through the odin project and I have came across a section where callbacks are used instead of async/await. I have read some of the mongoose documentation regarding the matter without any luck.

Here is an example I am working with:

passport.use(
    new LocalStrategy((username, password, done) => {
        User.findOne({username: username}, (err, user) => {
            if (err) {
                return done(err)
            }
            if (!user) {
                return done(null, false, {message:"Incorrect Username"})
            }
            if (user.password !== password) {
                return done(null, false, {message: "Incorrect password"})
            }
            return done(null, user)
        })
    })
)

I understand most of what is going on here, but I do not understand how this is able to function without the use of async/await. I am looking specifically at the line:

User.findOne({username: username}, (err, user) => {callback})

My guess is that the database is queried, and if the user is found the data from the query is stored in the parameter "user."

If the query fails and no data is returned, then user becomes null and our err parameter will contain a message.

Is this correct?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use simple concept

async getUserList(){
  try{
     const users = User.findOne({username: username});
     return users;
  }catch(error){
    throw error;
  }
}

call function anywhere

console.log(getUserList());

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