首页 > 解决方案 > 异步 Mongo DB 查询

问题描述

在我的代码中,我正在向我的 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'
}

非常感谢

标签: javascriptnode.jsmongodb

解决方案


将代码更新为以下内容:

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的方式。您正在为每个函数调用建立一个数据库连接。当您有大量请求时,这很快会导致数据库端的连接用完。

将 DB 连接建立部分移至普通位置并重新使用该连接。


推荐阅读