A
A
Arseniy Kornilov2020-12-22 13:44:27
JavaScript
Arseniy Kornilov, 2020-12-22 13:44:27

How to solve the problem (NodeJS, Mongodb)?

Good afternoon!
I often encounter this problem: I need to find all the documents by ObjectId that are contained in some array, but the response is sent before the loop starts.

node.js, express

var list = [];
for (var i = 0; i < result.items.length; i++) {
    Mongo.Items.findOne({'_id': ObjectId(result.items[i])}, function(err3, result3) {
        if (err3) return console.log(err3), response.sendStatus(500);
        if (result3) list.push(result3)
     });
}
return response.send(list);   // интерпретатор сразу отправляет результат (пустой массив list), обходя цикл for

result.items - Result of the previous database search, ObjectId array Any help would be

appreciated!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-12-22
@badcarrot

async/await

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question