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."
});
});
}