0

I would like to retrieve an array from my mongodb collection, and before sending it back to the client, work with it. My desired outcome would be the following:

  • Get array from collection_A
  • Do the desired work with the array I just got, by having another mongodb query
  • Pass the array back to the client

My current code looks like this:

                db.collection("collection")
                .find()
                .toArray()
                .then((arr) => {
                    arr.forEach(cur => {
                        db.collection("another-collection")
                            .count({key: cur.prop})
                            .then((retrieved) => {
                                cur.prop = retrieved; //The amount of count one live above
                                //This part runs later than the res.success below
                            })
                            .catch((err: any) => {
                                //Handle error
                            });
                    });
                    return arr;
                })
                .then(arr => {
                    res.success(arr);
                })
                .catch((err) => {
                    //Handle error
                });

At the moment, the work I want to do with the retrieved array happens after res.success(), so on the client I will get the original array. Why is that so?

D. Albert
  • 25
  • 5

1 Answers1

0

You can use Promise.all along with Array#map.

.then((arr) => 
    Promise.all(arr.map(cur => 
        db.collection("another-collection")
            .count({
                key: cur.prop
            })
            .then((retrieved) => {
                cur.prop = retrieved; 
                return curr;
            })
            .catch((err: any) => {
                //Handle error
            })
    ))
)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • This way the array I'm sending back in success is undefined for some reasons – D. Albert Nov 30 '21 at 18:56
  • @D.Albert Do you have a return statement in `.then` after `db.collection(...)`? If not, add return `curr` or whatever you want to return. – Unmitigated Nov 30 '21 at 18:57
  • I'm not sure at which part should I put the return statement. Can you please demonstrate it in your code? If Promise.all returns a promise with the device, then I suppose I should put it after promise.all, however my IDE shows unreachable code for the below part. – D. Albert Nov 30 '21 at 19:06
  • @D.Albert I've updated my answer, but it's not exactly clear what you want to return as the result. – Unmitigated Nov 30 '21 at 19:07
  • I want to manipulate every element of the array I got from the first query, then return the manipulated array to send it back to the client – D. Albert Nov 30 '21 at 19:11
  • @D.Albert Change `return retrieved;` in my edited answer to `return curr;` then. – Unmitigated Nov 30 '21 at 19:11