What is the best way to iterate through results in a Realm custom resolver function when receiving a response from the

My goal is to develop a function for my custom resolver that retrieves all documents in a collection and updates the payload with new data. The code snippet below illustrates how I am currently getting one client and modifying its information:

exports = (input) => {
  const clientId = input._id;
  const openStatusId = new BSON.ObjectId("898999");
  
  const mongodb = context.services.get("mongodb-atlas");
  const clientRecords = mongodb.db("db-name").collection("clients");
  const jobRecords = mongodb.db("db-name").collection("jobs");
  
  let client = clientRecords.findOne({"_id": clientId});
  const query = { "client_id": clientId};

  let jobsForClient = jobRecords.count(query)
  .then(items => {
    console.log(`Successfully found ${items} documents.`)
    // items.forEach(console.log)
    return items
  })
  .catch(err => console.error(`Failed to find documents: ${err}`));
  
  let openJobs = jobRecords.count({"client_id": clientId,"status": openStatusId})
  .then(numOfDocs => {
    console.log(`Found ${numOfDocs} open jobs.`)
    // items.forEach(console.log)
    return numOfDocs
  })
  .catch(err => console.error(`Failed to find documents: ${err}`));
  
  return Promise.all([client, jobsForClient, openJobs]).then(values => {
    return {...values[0], "jobs": values[1], "openJobs": values[2]}
  })
};

I would like to enhance this function to retrieve all clients and iterate over each one to add data: By changing this line: let client = clientRecords.findOne({"_id": clientId}); to this: let clients = clientRecords.find();

After retrieving all documents from the clients collection with the updated code above, how can I loop through each client?

UPDATE:

I have made modifications to the function as shown below, which functions correctly within the realm environment but throws an error when executed as a GraphQL query.

Updated code:

exports = (input) => {
  const openStatusId = new BSON.ObjectId("999999");
  
  const mongodb = context.services.get("mongodb-atlas");
  const clientRecords = mongodb.db("db-name").collection("clients");
  const jobRecords = mongodb.db("db-name").collection("jobs");
  
  const clients = clientRecords.find();

  const formatted = clients.toArray().then(cs => {
    return cs.map((c,i) => {
      const clientId = c._id;
      const query = { "client_id": clientId};
      
      let jobsForClient = jobRecords.count(query)
      .then(items => {
        console.log(`Successfully found ${items} documents.`)
        // items.forEach(console.log)
        return items
      })
      .catch(err => console.error(`Failed to find documents: ${err}`));
      
      let openJobs = jobRecords.count({"client_id": clientId,"status": openStatusId})
      .then(numOfDocs => {
        console.log(`Found ${numOfDocs} open jobs.`)
        // items.forEach(console.log)
        return numOfDocs
      })
      .catch(err => console.error(`Failed to find documents: ${err}`));
      
      return Promise.all([jobsForClient, openJobs]).then(values => {
        return {...c, "jobs": values[0], "openJobs": values[1]}
      });
    })
  }).catch(err => console.error(`Failed: ${err}`));
  
  return Promise.all([clients, formatted]).then(values => {
        return values[1]
      }).catch(err => console.error(`Failed to find documents: ${err}`));
};

Error in GraphQL: "message": "pending promise returned that will never resolve/reject",

Answer №1

If you want your function to wait for the final promise to resolve before returning, consider implementing something along these lines:

module.exports = async (input) => {

    ...

    let values = await Promise.all([jobsForClient, openJobs]);
    return {...c, "jobs": values[0], "openJobs": values[1]};
}

Answer №2

Resolved the issue with mongodb aggregate method. See the solution provided below:

exports = async function(input) {


const openStatusId = new BSON.ObjectId("xxxxxx");
  
  const mongodb = context.services.get("mongodb-atlas");
  const clientRecords = mongodb.db("xxxxx").collection("xxxx");
  const jobRecords = mongodb.db("xxxxx").collection("xxxx");
  
  return clientRecords.aggregate([
      {
          $lookup: {
              from: "jobs",
              localField: "_id",
              foreignField: "client_id",
              as: "totalJobs"
          }
      },
      {
          $addFields: {
            jobs: { $size: "$totalJobs" },
            openJobs: {
              $size: {
                $filter: {
                  input: "$totalJobs",
                  as: "job",
                  cond: { "$eq": ["$$job.status", openStatusId]},
                }
              }
            },
          }
      }
  ]);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js SQLite3 - DB.each() not running the subsequent code block

When running the code snippet below, I am getting the following output: var db = new sqlite3.Database("database.sqlite") console.log("2") db.each("SELECT * FROM gban WHERE id = '"+id+"'", async functi ...

Having difficulty importing app.js into other modules within ExpressJS

Having trouble importing app.js into other modules in ExpressJs. It imports successfully, but I can't use the functions defined in the app.js file. The code snippet I am working with is as follows: I have this app.js var app = express(); var express ...

What is the best way to reference an object within the Vue data as the value of an item?

If I wanted to incorporate the {{ $t('index-p1') }} value within the title property, how would I do so? items: [ { icon: 'mdi-apps', title: 'Welcome', to: '/' }, For int ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Can a file be successfully retrieved using an HTTP POST request?

Can a file be downloaded using HTTP POST method? I am aware of the "Get" method (windows.location), but in my scenario, there are many parameters that need to be sent to the server. ...

Disappearing text editor content in React Js

I have created a basic accordion feature with a text editor inside each accordion. Accordion.js <div className="wrapper"> {accordionData.map((item, index) => ( <Accordion> <Heading> <div styl ...

Is there a way to ensure that functions operate effectively within a modal window?

While working on a script for my job, I decided to move most of my HTML content into a modal halfway through writing the code. The challenge now is that many functions I've already created no longer work with the content inside the modal. I'm hop ...

Retrieving multiple embedded documents from an array in mongodb

Struggling with crafting a query that compares a specific value against a particular field in all embedded documents within an array. To help illustrate the issue, consider this scenario: Imagine using MongoDB to save the latest queries made by users on y ...

Running the command "npm start" will keep your application running indefinitely

Even when the status shows online, I am still unable to run the port on 8014. Whenever I try using pm2 to start tools/srcServer.js "scripts": { "prestart": "babel-node tools/startMessage.js", "start": "npm-run-all --parallel test:watch open:src", "ope ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

sort options by a different dropdown selection

Currently, I am attempting to utilize the value selected in one dropdown to filter the options displayed in the subsequent dropdown. Both dropdowns are populated with data retrieved from several JSON files (as illustrated below). The objective here is to ...

The Navbar in my React Material UI app is being covered by the Drawer component. Can someone guide me on how to fix

I am facing an issue where the drawer is overlaying my navbar instead of disappearing behind it when opened. I tried adjusting the z-index in my styles but it doesn't seem to be working as expected (see screenshot). The z-index for the navbar is set h ...

Is there a way to transfer the chosen maximum and minimum price values to a JavaScript function within a select tag in HTML?

I have a search form that includes select options with two values. However, I want to have two select options for both the Max and Min price values. <input type="hidden" id="budget_min" name="filter_budget_min" value="0" /> <select onchange="upda ...

I encountered the following error: Failed to parse due to the module '@babel/preset-react' being missing

Encountering a parsing error: Module '@babel/preset-react' cannot be found. Upon creating schema.js, tweetSchema.js, userSchema.js, issues arose with import, export, and export from all three files showing red lines. schema.js: import createSche ...

Having trouble setting up node-gyp on ubuntu

npm http 200 https://registry.npmjs.org/weak/-/weak-0.2.2.tgz npm http GET https://registry.npmjs.org/bindings npm http 304 https://registry.npmjs.org/bindings > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dfcdc9c3e898 ...

What is the best way to append data to the right side of a Datatable?

I am currently working with a DataTable and have a chart below it. Currently, my setup looks like this: Below is the HTML code I am using: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content- ...

Remove the Ajax-SliderExtender upon refreshing the page with the F5 key

While working with an Ajax SliderExtender in an UpdatePanel, I assigned a BehaviorID and invoked the $find('behavorID').add_valueChanged function within the $document.Ready. Everything seemed to be working fine until I encountered an issue where ...

What is the best way to implement dynamic comment display similar to Stack Overflow using Asp.net and Jquery?

I have created a small web application using Asp.net and C#. Currently, I am able to retrieve comments by refreshing the entire page. However, I would like to achieve this functionality without having to do a full refresh. For instance Let's say the ...

Obtain additional information to address concerns related to onZoom and onPan issues on the line

Attempting to enhance my Chart.js line chart by fetching more data or utilizing cached backup data during onZoom/onPan events has proven quite challenging. The original code base is too intricate to share entirely, but I will outline the approaches I have ...

What is the best way to combine two JSON objects?

Item A: var item1 = { "roleid": "001", "techid": "001", "role": "WEB DEVELOPER", "tech": "JAVASCRIPT", "experience": [], "certifications": [], "gender": ["Male"], "awards": [], "min_experience_years": "4", "max_expe ...