gpt4 book ai didi

node.js - 两个forEach执行完毕后res.send

转载 作者:太空宇宙 更新时间:2023-11-04 02:08:48 25 4
gpt4 key购买 nike

const collect = [];
req.body.product.forEach(function(entry) {
mongoClient.connect(databaseServerUrl, function(err, db) {
let testCollection = db.collection('Tests');
testCollection.find({Product: entry}).toArray((err, docs) => {
let waiting = docs.length;
docs.forEach(function (doc) {
collect.push(doc);
finish();
});
function finish() {
waiting--;
if (waiting === 0) {
res.send(collect);
}
}
});
db.close();
});
});

这只是拿回第一组。例如,如果我的 req.body.product 数组中有两个 Node 。我只拿回第一盘。但我需要取回所有内容,而不仅仅是从一个集合中取回。

最佳答案

我建议执行一个查询来获取所有结果,而不是执行两个查询并将结果合并到一个数组中,如下所示:

mongoClient.connect(databaseServerUrl, function(err, db) {
const query = { $or: req.body.product.map(Product => ({ Product })) };
db.collection('Tests').find(query).toArray((err, docs) => {
// ...handle `err` here...
res.send(docs);
db.close();
});
});

请注意,我还没有对此进行测试,因为我面前没有 MongoDB 数据库。

关于node.js - 两个forEach执行完毕后res.send,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43188905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com