Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda