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

297
Views
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 answers
Answer question

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 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!