0

Whenever I try to push into the pathItem array, the response is an empty array. What is happening?

        const categories = await Cars.find().distinct("bodytype");
        let pathItem = [];
        categories.forEach(async (element) => {
          const countQuery = await Cars.countDocuments({
            bodytype: element,
          });
          const numberOfPages = Math.ceil(countQuery / 12);
          for(let count=1; count<=numberOfPages; count++) {
          const carPath = {paths: { cartype: element, pages: count }}
            pathItem.push(carPath)
          }
        });
        console.log(pathItem) // this returns an empty array
4
  • 6
    forEach will not wait for async calls. Use for of Commented Jun 21, 2021 at 18:17
  • 3
    You could also do this in parallel using Promise.all Commented Jun 21, 2021 at 18:19
  • Thanks a lot. That helped. Didn't know forEach does not wait for async calls. Commented Jun 21, 2021 at 18:39
  • 1
    @greyShader can you please add an answer to your question to help future question visitors? Commented Jun 21, 2021 at 21:45

1 Answer 1

4

This is what worked:

        const categories = await Cars.find().distinct("bodytype");
        let pathItem = [];
        for(let elements of categories) {
          const countQuery = await Cars.countDocuments({
            bodytype: element,
          });
          const numberOfPages = Math.ceil(countQuery / 12);
          for(let count=1; count<=numberOfPages; count++) {
          const carPath = {paths: { cartype: element, pages: count }}
            pathItem.push(carPath)
          }
        });
        console.log(pathItem) // this does not returns an empty array anymore

As Tushar mentioned, forEach does not wait for async calls, so Mongoose requests were not fulfilled before the forEach exited each loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.