简体   繁体   English

Mongoose:了解回调与异步/等待

[英]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.我试图理解 mongoose 中的回调。我真的只是想澄清我的理解,这样我就可以确定我在正确的轨道上。

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.我了解使用 async/await 在 mongodb 中使用 mongoose 进行查询。例如,假设我的 model“用户”设置正确,以下代码将从我的数据库中获取用户。

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.我正在研究 odin 项目,我遇到了一个使用回调而不是 async/await 的部分。 I have read some of the mongoose documentation regarding the matter without any luck.我已经阅读了一些关于此事的 mongoose 文档,但没有任何运气。

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.我明白这里发生的大部分事情,但我不明白如果不使用 async/await,这是如何做到 function 的。 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."我的猜测是查询数据库,如果找到用户,查询的数据将存储在参数“user”中。

If the query fails and no data is returned, then user becomes null and our err parameter will contain a message.如果查询失败并且没有返回数据,则用户变为 null,我们的 err 参数将包含一条消息。

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随时随地拨打 function

console.log(getUserList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM