res.send 两个forEach执行完后

res.send after two forEach have finished executing

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 数组中有两个节点。我只拿回第一盘。但我需要取回所有东西,而不仅仅是从 Collection.

您的 mongoClient.connect() 是异步的,但您的循环只是在不等待回调的情况下执行。

尝试异步 forEach 循环:enter link description here

这应该可以解决您的问题

与其执行两个查询并将结果合并到一个数组中,我建议执行一个获取所有结果的查询,它看起来像这样:

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 数据库。