Search code examples
node.jsapi-design

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();
    });
});

this is only getting back the first set. If I have two nodes in my array of req.body.product for example. I am only getting back the first set. But I need to get back everything not just from one Collection.


Solution

  • Rather than performing two queries and combining the results into one array, I suggest performing a single query that gets all of the results, which would look something like this:

    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();
        });
    });
    

    Note that I haven't tested this since I don't have a MongoDB database in front of me.