异步 Mongo 数据库查询

时间:2021-02-01 10:40:46

标签: javascript node.js mongodb

在我的代码中,我向我的 Mongo 数据库发送查询。方法 findUser() 应返回此查询的响应。查询工作正常,已使用 console.log(users) 进行测试。 问题是函数返回null,它不会等到查询得到响应才返回var foundUser。 在这种情况下,我如何使用 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) 输出:

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

非常感谢

3 个答案:

答案 0 :(得分:2)

将代码更新为以下内容:

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;
};

并使用 await findUser(username);

调用该函数

注意: 不推荐使用以上连接数据库的方式。您正在为每个函数调用建立一个数据库连接。当您有大量请求时,这会很快导致数据库端的连接用尽

将DB连接建立部分移到通用位置,重新使用连接。

答案 1 :(得分:1)

无论你做什么,你对数据库执行的任何操作,它都会返回promise,所以在第1行你的函数名之前写async关键字,然后在你的查询之前写await关键字6,然后它会像同步调用一样,每一行都会相应地执行

答案 2 :(得分:1)

如您所说,异步方法需要使用 async/await 运算符。

你有两个选择:

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)使用函数直接返回结果

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;
}
相关问题