0

I have a route which performs 2 queries in 2 different databases like so:

app.post('/location',function(req,res){

    Db.find({id:anId},function(err,doc){
        myDocs=[]
        for (var i = doc.length - 1; i >= 0; i--) {
            myDocs.push(doc[i])
            otherDocs=[]
            otherDb.find({id:doc[i].id},function(err,doc2){
                for (var i = doc2.length - 1; i >= 0; i--) {
                    otherDocs.push(doc2[i])
                }
            })
            myDocs.push(otherDocs)
        }
        res.send(myDocs)
    })

})

The issue here is that otherDocs is local to the anonymous function in otherDb, I am not able to access it from outside and push it into myDocs. How would I be able to do this?

m0bi5
  • 8,900
  • 7
  • 33
  • 44

1 Answers1

3

You don't have a scoping problem, you have an asynchronous problem. Because the inside of your loop has asynchronous code, you'll have to wait for the callbacks to finish first before pushing them to myDocs and res.sending them.

Easiest solution to this would be to make the function async and then await each inner .find (transformed into a Promise):

app.post('/location',function(req,res){
  Db.find({id:anId}, async function(err,doc){
    const myDocs = [];
    for (const oneDoc of doc.reverse()) {
      myDocs.push(oneDoc);
      const doc2 = await new Promise(res => {
        otherDb.find({id: oneDoc.id}, (err,doc2) => res(doc2));
      });
      myDocs.push(doc2.reverse());
    }
    res.send(myDocs);
  });
});

Note that this will iterate through each oneDoc's find one-by-one - if you want to send all requests at once rather than in parallel, use Promise.all instead.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320