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?
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());