javascript - Node MongoDB 循环遍历集合的第一条记录并将其推送到数组中
问题描述
我正在尝试按数字集合名称获取用户名列表。我已经创建了查询,似乎工作正常,但它没有推入数组,所以我可以返回整个数据作为对 api 的响应。
router.get('/chat-logs', async (req, res) => {
const collections = Object.keys(db.db.collections);
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, dbm) {
if (err) throw err;
var dbo = dbm.db('dbname');
let collections = dbo
.listCollections()
.toArray()
.then(data => {
let names = [];
forEach(data, function(e) {
let { name } = e;
if (!isNaN(name)) {
dbo.collection(name).findOne({}, function(err, result) {
if (err) throw err;
names[name] = `${result.first_name} ${result.last_name}`;
});
}
});
console.log(names)
res.send(names);
});
});
});
如您所见,我正在获取所有集合名称,因为聊天日志与其相应的 ID 一起存储为集合,并且我正在循环它们并获取它们的最后一个字段。最后,我尝试将其推送到 names[] 数组中,以便我可以将它们全部收集并发送响应。问题是数组在查询范围之外仍然是空的。我有点卡在这一点上,我想知道是否有更简单的方法可以将所有集合的最后一个字段作为数组获取,如果没有,那么我该如何解决这个问题?
谢谢
解决方案
请参阅Node JS Promise.all 和 forEach
您也许可以执行以下操作:
router.get('/chat-logs', async (req, res) => {
const collections = Object.keys(db.db.collections);
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, dbm) {
if (err) throw err;
var dbo = dbm.db('dbname');
let collections = dbo
.listCollections()
.toArray()
.then(data => {
let names = [];
i = 0;
data.forEach(function(e) {
let { name } = e;
if (!isNaN(name)) {
dbo.collection(name).findOne({}, function(err, result) {
if (err) throw err;
names.push(`${result.first_name} ${result.last_name}`);
i=i+1;
if(i>(names.length-1)){
// all callbacks have finished.
console.log(names)
res.send(names);
}
});
}
});
});
});
});
推荐阅读
- c# - 如何删除单元格间距。表 CellSpacing 为零,不起作用
- reactjs - 无法在“DOMWindow”上执行“postMessage”
- azure - Azure 服务总线即将发生的变化
- java - 使用java对ArrayList的相关记录进行分组并放入HashMap
- typescript - 使用 Jest 测试 typescript 异步函数
- tomcat - centos上的wso2-apps需要安装tomcat吗?
- html - 如果 Email1 和 Email2 重复,则更改输入的颜色
- xamarin - GTIN 无法转换为系统字符串
- java - 如何编写 Comparator.comparing
- angular - 多个 mat-select 不显示正确的值