javascript - 如何从 MongoDB 函数中的函数获取变量?
问题描述
我有:
var url = "mongodb+srv://exampleuser:53pr1WkCUkkOon0q@cluster0-zfo5z.mongodb.net/test?retryWrites=true&w=majority&useUnifiedTopology=true";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("rw_bewerbung");
var query = { mc_uuid: uuid };
dbo.collection("user_name_history").find(query).toArray(function(err, result) {
if (err) throw(err);
nameHistory = result[0].name_history;
db.close();
});
});
我想得到变量 nameHistory ......我该怎么做?
解决方案
您可以通过将代码转换为承诺来做到这一点:
const bewerbung = async (url) => new Promise((resolve, rejected) => {
MongoClient.connect(url, function(err, db) {
if (err) {
rejected(err);
} else {
const dbo = db.db("rw_bewerbung");
const query = {mc_uuid: uuid};
dbo
.collection("user_name_history")
.find(query)
.toArray(function (err, result) {
if (err) {
rejected(err);
} else {
db.close();
resolve(result[0]);
}
});
}
});
}).catch(console.error);
const url = "todo...";
const res = await bewerbung(url);
const nameHistory = res.name_history;
console.info('nameHistory', nameHistory);
.
推荐阅读
- javascript - 在反应中使用 useContext 时遇到问题?
- javascript - 如何从 puppeteer/playwright JSelement 节点中删除子节点,然后获取 innerText
- google-sheets - 谷歌工作表应用程序不拒绝无效的日期验证输入
- elasticsearch - Elasticsearch 显示 logstash 索引的黄色运行状况
- typescript - 如何使用tailwindcss将样式文件夹移动到nextjs typescript中的src文件夹?
- r - 使用enrichKEGG() 的结果制作点图
- python - 出现“要输出多个子图,正在清除包含传递轴的图形”消息并且找不到解决方法
- java - Java Lambdas:带有 PriorityQueue 的比较器
- python - 使用 django 让 EMPID 在 html 中显示
- mongodb - 需要从 mongodb 中的对象获取所有密钥