javascript - 异步 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'
}
非常感谢
解决方案
将代码更新为以下内容:
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 连接建立部分移至普通位置并重新使用该连接。
推荐阅读
- botframework - 禁用用户输入文本框c#
- c# - 验证 JSON 序列化/反序列化为 c# double
- react-native - React Native - addnavigationHelpers 未定义
- angular - Angular 应用程序中的声明式和反应式方法之间的摩擦
- vim - vim中是否有类似于f命令的多个字符?
- javascript - React Js:从对象数组中更新一项
- javascript - 解析数据时出现错误。我该如何解决?
- docker - Docker:文件系统没有响应
- webpack - 如何根据第三方提供的 chunk.js 渲染页面
- android - setIsStrongBoxBacked() for 没有按预期抛出 StrongBoxUnavailableException