0

I'm creating an API on Node with MongoDB, I'm learning slowly. When creating a GET route, I'm experiencing a problem, the request response is sent before going through the implemented logic. In the code, the line res.send(listClass); it always is executed first, just after this the foreach is executed.

exports.getClassrooms = (req, res) => {
    const listClass = [];
    const query = {"userId": req.params.id};
    classUser.find(query, (err, result) => {
        if(result){
            result.forEach(data => {
                classroom.findById({"_id": data.classId}, (err, doc) => {
                    if(doc){
                        listClass.push(doc);
                    }
                });
            });
        }
        res.send(listClass); 
    }).catch( err => {
        res.status(500).send({
           message: err.message || "Erro to find the class."
        });
    });
}
Bruno Inácio
  • 75
  • 1
  • 2
  • 8
  • You are actually trying to ***perform a "join" of related data***. Instead, use [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) to return the results in a single request., rather than looping many calls to the database and trying to control when that "loop" returns. – Neil Lunn May 04 '19 at 03:35

1 Answers1

0
var async = require('async');
exports.getClassrooms = (req, res) => {
    const listClass = [];
    const query = { "userId": req.params.id };
    classUser.find(query, (err, result) => {
        if (result) {
            var i = 0;
            async.whilst(function () {
                return i <= result.length
            },
                function (next) {
                    classroom.findById({ "_id": data.classId }, (err, doc) => {
                        if (doc) {
                            listClass.push(doc);
                        }
                    });
                    i = i + 1;
                    next();
                },
                function (err) {
                    res.send(listClass);
                }
            )
        }

    }).catch(err => {
        res.status(500).send({
            message: err.message || "Erro to find the class."
        });
    });
}

classroom.findById function is not syncronize function, this function is asynchronous function.
So, we can use async library,
There are serveral method for this problem, and I used whilst function

Also, we can use await/async instead async library.

Wang Liang
  • 4,244
  • 6
  • 22
  • 45