简体   繁体   English

异步 Mongo 数据库查询

[英]Async Mongo DB Query

In my code, I am sending a query to my Mongo database.在我的代码中,我正在向我的 Mongo 数据库发送一个查询。 The method findUser() shall return the response of this query. findUser()方法应返回此查询的响应。 The query works fine, tested with console.log(users) .查询工作正常,用console.log(users)测试。 The problem is the function returns null , it doesn't wait till the query got a response to return the var foundUser .问题是 function 返回null ,它不会等到查询得到响应才返回var foundUser How could I use await/async in this case in order to wait for the query response before returning anything?在这种情况下,我如何使用await/async以便在返回任何内容之前等待查询响应?

function findUser(username) { 
    foundUser = null
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology : true});
    client.connect(err => {
        const collection = client.db("YourCV").collection("Accounts");
        result = collection.findOne({username : username }, function(err, user) {
            console.log(user)
            if(user){
                foundUser = user
            }
        });
    });  
    return foundUser
};

console.log(user) outputs: console.log(user)输出:

{
  _id: 601695084b28102500ae0015,
  username: 'jetlime',
  password: '$2b$10$EN5k/YKOMBgibqy62s0hGOX9MffHZtXkfsw0Du0j8QVS7mGab5FLi'
}

Many thanks非常感谢

Update the code to the following:将代码更新为以下内容:

async function findUser(username) {
    const client = await MongoClient.connect(url, { useNewUrlParser: true })
        .catch(err => { console.log(err); });

    if (!client) {
        return;
    }
    const collection = client.db("YourCV").collection("Accounts");
    const user = await collection.findOne({username : username });
    client.close(); // -> To be under finally clause.
    return user;
};

And call the function with await findUser(username);并使用await findUser(username);

Caution: The above of connecting to DB is not recommended.注意:不推荐以上连接DB的方式。 You are establishing a DB connection for every function call.您正在为每个 function 调用建立数据库连接。 This quickly leads to running out of connections on the DB side when you have a large number of requests .当您有大量请求时,这很快会导致数据库端的连接用完。

Move the DB connection establishing part to a commonplace and re-use the connection.将 DB 连接建立部分移至普通位置并重新使用该连接。

See whatever you do, any operation you perform with your database, it returns promise, so write async keyword before the name of your function in line 1 and then await keyword before your query in line 6, it will then behave like synchronous call and every line will execute accordingly查看您所做的任何操作,您对数据库执行的任何操作,它都会返回 promise,因此请在第 1 行的 function 的名称之前写入async关键字,然后在第 6 行的查询之前写入await关键字,然后它将表现得像同步调用和每个行将相应地执行

As you said, you need to use async/await operators for asynchron methods.正如您所说,您需要将 async/await 运算符用于异步方法。

You have two choices:你有两个选择:

1)Implement callback method on findUser 1)在findUser上实现回调方法

  async function findUser(username, onUsersReady) {
    const client = new MongoClient(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }).connect();

    const collection = await client.db("YourCV").collection("Accounts");
    await collection.findOne({
      username: username
    }, function(err, user) {
      console.log(user)
      if (user) {
        foundUser = user
        onUsersReady(user);
      }
    });
  };

2)Use function to return results directly 2)使用function直接返回结果

async function findUser(username) {
  const client = await new MongoClient(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }).connect();

  const collection = await client.db("YourCV").collection("Accounts");
  const foundUser = await collection.findOne({
    username
  });
  return foundUser;
}

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

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