javascriptmongodbmongodb-querymongodb-realm

Pass 1 sync and 1 async variables to next async function


I am using mongodb realm with a simple custom query function to return DB data

  function mongo(data) {
    return fetch(
      apiurl,
    {
      method: "POST",
       headers: {
          "Content-Type": "application/json",
       },
        body: JSON.stringify(data),
       }
    )
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log("Success:", data);
      return data;
    })
    .catch((error) => {
      console.error("Error:", error);
    });
  }

  mongo({
    collection: "metadata",
    action: "find",
    criteria: { query: {}},
  }).then((metadata) => {
    for (var i = 0; i < metadata.length; i++) {
      var oneMeta= metadata[i];
      var subjectName = oneMeta.name;
      var subjectCode = oneMeta.code;
      var blockHTML =
        `<div>
        <span class="badge badge-danger">` + subjectName + `</span>
        <span class="badge badge-dark">` + subjectCode + `</span>
        </div>`;
      var oneSubject = document.createElement("div");
      oneSubject.id = "sub_"+subjectCode 
      oneSubject.innerHTML = blockHTML;
      subjectOutput.appendChild(oneSubject);
    }
  });

I was trying to do another mongo({collection: "actualData", action: "count", criteria: { query: {subjectId: XXX}}}) query for each metadata where XXX would be subjectCode from metadata[i]

The goal is to append another <span>count</span> to the DIV created above using its id, where the count is the result of the second mongo function.

I was only able to do it without looping metadata.length

I need to do the next function for every time in the loop, while using i and metadata

Any help appreciated!


Solution

  • Just map your metadata to an array of mongo promises, await all of them, then the count result will be in the same position of the array:

    mongo({
        collection: "metadata",
        action: "find",
        criteria: { query: {}},
      }).then(async (metadata) => {
        const counts = await Promise.all(metadata.map((oneMeta) => {
          return mongo({collection: "actualData", action: "count", criteria: { query: {subjectId: oneMeta.subjectCode}}});
        }));
        for (let i = 0; i < metadata.length; i++) {
          const count = counts[i];
          const oneMeta = metadata[i];
          const subjectName = oneMeta.name;
          const subjectCode = oneMeta.code;
          var blockHTML =
              `<div>
              <span class="badge badge-danger">` + subjectName + `</span>
              <span class="badge badge-dark">` + subjectCode + `</span>
              <span class="badge badge-dark">` + count + `</span>
              </div>`;
          var oneSubject = document.createElement("div");
          oneSubject.id = "sub_"+subjectCode 
          oneSubject.innerHTML = blockHTML;
          subjectOutput.appendChild(oneSubject);
        }
    })