Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query:

ReferenceError: Users is not defined

While this behavior is expected, I prefer to organize my resolvers in separate files for better modularity, rather than including them all in index.js. My current file structure looks like this:

Current file structure

index.js 
  /graphql
    /typdef
      user.graphql
    /resolver
      user.js

The user.graphql schema works correctly; it's just the user.js causing errors due to the unavailable Users variable.

Below are snippets of index.js and user.js.

index.js

(Code from index.js goes here.)

user.js

(Code from user.js goes here.)

I'm looking for the best way to pass the MongoDB or the Users collection to the resolver files. Alternatively, if there is a better solution to address this issue altogether.

Answer №1

Initially, it's important to note that this solution may not be considered best practice since using global variables alongside an outsourced schema is generally discouraged. However, in this specific case, it proved effective and could potentially spark ideas for future improvements.

To address the issue, I simply adjusted the variable from a local const to a global.

In index.js, the line

const Users = db.collection('user')
was modified to
global.Users = db.collection('user')
.

The same modification was made in user.js. The line

return (await Users.find({}).toArray()).map(prepare)
became
return (await global.Users.find({}).toArray()).map(prepare)
.

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

Passing an array with pre-defined variables using jQuery's Ajax functionality

Currently, I have a function set up to gather the contents of a form and send it to a PHP page for processing. However, I am facing an issue where no data is reaching the PHP page when sending it via POST or GET methods. function add_new_customer(){ $ ...

Showing up getting a string instead of a boolean

This is a recurring question that has been asked multiple times, but none of the previous answers addressed the sending method. Furthermore, the solution provided previously does not work for me. My specific issue involves trying to retrieve a boolean val ...

Issue with POST request failure in Mongodb, React, Node, and Express

I've been attempting to execute a post request from a React front-end using jQuery Ajax calls. However, no matter what I try with app.post, it appears that no data is being sent to the database. All I get is an empty {} when "completed send" is displa ...

Updating results in Angular.js based on variable changes

After setting some data in the window, I am facing issues with updating an angular.js table created using the smart table module/plugin. The data is structured like this: window.checker={};window.checker.checked = [{'ip':9,'port':0}] ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Tips for directing the scroll according to the current selection class

I am attempting to focus the scroll based on the selected class when clicking on the previous and next buttons. How can I achieve this functionality? Please review my code on https://jsfiddle.net/kannankds/bcszkqLu/ <ul class="kds"> <li>tile ...

Tips for properly implementing ng-hide and ng-show across various sections of your single page application

Currently working on a Single Page Application (SPA). I've included some buttons in the side navigation with the intention of displaying different content when they are clicked. However, I encountered an issue where using ng-hide and show didn't ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

The data in my AngularJS model will only refresh when the button is clicked twice

I am encountering an issue with a select list box and a button in my code. The aim is to filter the model displayed in the select list box based on the selectId received from clicking the button. The problem arises when the model updates only after clicki ...

What is the best way to eliminate the comma at the end of the final array

<% for(var i=0; i < 10; i++) { %> <a href="#"><%= related[i] %></a><% if(i !== 9) { %>, <% } %> <% } %> Displayed above is some code that includes a loop to display related items. The goal is to remove the comm ...

Surprising Regex Match of ^ and special character

My regular expression is designed to break down calculator input strings, such as 12+3.4x5, into individual tokens like 12, +, 3.4, x, and 5 Here is the regular expression I am using: \d+\.?\d+|[\+-÷x] However, I am encountering une ...

Issues with sending post parameters in Uploadify with NodeJS

I'm currently working on my new app using nodeJS and I'm in the process of implementing the functionality to upload multiple files. I decided to integrate the Uploadify flash-based file uploader to achieve this. However, I've encountered an ...

The RegisterHelper feature seems to be malfunctioning in handlebars

Just starting out with NodeJs and Handlebars. I am passing an array of values to the view and have created a helper function to determine whether or not to include a "View all" action button based on the length of the array. If the length is greater than 1 ...

Utilize Javascript to extract information from an array of XML objects

I have an XML object that I need to parse in order to extract startdate and end date data. My goal is to compare and group appointments with the same date together, but I don't have much experience manipulating XML - I'm more comfortable with JSO ...

Error: There was an issue registering the component as the target container is not recognized as a valid DOM element

Upon executing the React code below, I encountered the following error: import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <div id="root"> <h1>Hello, world!</h1></div>, document ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

Please refrain from using res.send(status, body) as it is now deprecated. Instead, use res.status(status)

file name script.js. I encountered an error while running my CRUD application. The specific line of code where the error occurs is causing some trouble. Can anyone provide a solution, please? If you need to see the complete code, let me know and I will p ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Prevent unauthorized users from accessing a page in a React application

As a novice in the field of software development, I find myself embarking on the journey of creating a React web application tailored for use at a medical clinic. At its core, this application will cater to just two types of users - patients and doctors. ...