Utilizing DataLoader in tandem with Mongoose: A comprehensive guide

I am currently working on implementing DataLoader with Mongoose for the following use case:

export const PurchaseOrderType = new GraphQLObjectType({
    name: "PurchaseOrder",
    description: "PurchaseOrder",
    interfaces: () => [NodeInterface],
    isTypeOf: value => value instanceof PurchaseOrderModel,
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLID),
            resolve: obj => dbIdToNodeId(obj._id, "PurchaseOrder")
        },
        name: {
            type: new GraphQLNonNull(GraphQLString)
        },
        customer: {
            type: CustomerType,
            resolve: (source, args, context) => {
                return context.customerLoader.load(source.customer_id);
            }
        }
    })
});

export default () => {
    return graphqlHTTP((req, res, graphQLParams) => {
        return {
            schema: schema,
            graphiql: true,
            pretty: true,
            context: {
                customerLoader: customerGetByIdsLoader()
            },
            formatError: error => ({
                message: error.message,
                locations: error.locations,
                stack: error.stack,
                path: error.path
            })
        };
    });
};



export const customerGetByIdsLoader = () =>
    new DataLoader(ids => {
        return customerGetByIds(ids);
    });


export const customerGetByIds = async ids => {
    let result = await Customer.find({ _id: { $in: ids }, deletedAt: null }).exec();

    let rows = ids.map(id => {
        let found = result.find(item => {
            return item.id.equals(id);
        });

        return found ? found : null; << === found always undefined
    });

    return rows;
};

During the implementation, I encountered the following challenges while loading multiple PurchaseOrders:

  1. One specific customer_id is being repetitively called in the ids parameter of the DataLoader. For instance, the id 5cee853eae92f6021f297f45 is being requested across various loader calls, implying a possible cache malfunction.

  2. The variable 'found' remains false consistently when processing the read results, despite correctly comparing the ids.

Answer №1

To easily find a specific customer information, you can utilize the findOne method.

export const fetchCustomersByIds = async ids => {
   let customers = await Customer.find({ _id: { $in: ids }, deletedAt: null }).exec();
   const selectedRows = [];
   let promiseAll = ids.map(async (id) => {
      let foundCustomer = customers.filter(item => item.id.toString() === id.toString());
      if(foundCustomer) {
         selectedRows.push(foundCustomer[0]);
         return foundCustomer[0];
      }
      return null; 
   });
   await Promise.all(promiseAll);
   return selectedRows;
};

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

Tips for integrating custom images or icons into Onsen-UI:

I am currently utilizing the Onsen-UI framework along with AngularJS to create a mobile application. I want to incorporate custom images for buttons, but they appear blurry or unclear on certain mobile devices when the app is launched. Below is my code sn ...

retrieve content within an iframe via ajax

I currently have an iframe set up on the server side like this: <iframe frameborder="0" runat="server" style="width: 100%; height: 700px; background-color: #bacad3;" id="I1" name="I1" src="Page.aspx"></iframe> and I update the content dynamic ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

Retrieve the most recent entry for every value within a field collection

I have a collection containing multiple records with the same value for the "name" field. I am looking to retrieve only one record for each unique name, based on the latest creation date. Here is a sample aggregation code that I have attempted: db.m_coll ...

Turn on/off the webGL Context in webGL/three.js

I am currently working on an exciting project using three.js, and so far everything is going according to plan. The project involves displaying various meshes in different canvases, which has led me to encounter a particular issue. My goal for the project ...

Exploring the power of Selenium Webdriver in combination with JavaScript

Can someone help me figure out why I'm getting this error message: "Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to org.openqa.selenium.WebElement at canvasdrag.Canvas.main(Canvas.java:57)" WebElement elemen ...

Tips for keeping the options menu visible even when the video is paused

As I was creating my own customized Video player, I encountered an issue where I wanted the options bar/menu to disappear when the user became inactive. While I have managed to achieve this functionality, I still require the option bar to remain visible ...

Accessing specific route parameters in a Vue.js application can be easily achieved by following these steps

I'm dealing with a situation involving nested route settings let routes = [ { name: 'Admin', path: '/prod/:id', component: Admin, meta: { requiresAuth: true, title: 'Admin - Fraud tool' ...

Jquery selector failing to target correct <form> element within Shopify theme

I'm feeling a bit lost here! Trying to zero in on a form within my page and utilize jQuery's serializeArray() function to extract all the values from said form. <div class="page-width"> <header class="section-header ...

The textgeometry element is not appearing in the three.js scene

I've inserted a boxgeometry into the scene with the intention of adding text to indicate the side of the cube. However, I am encountering difficulties in incorporating textgeometry into the scene. This is my code: const loader = new FontLoader(); loa ...

Passing Down Instance Methods Using Static References in JavaScript/TypeScript

✋ Exploring the concept of access modifiers from TypeScript, how can we make it relevant for JavaScript developers as well? Let's consider a scenario where a parent class defines necessary members and a shared method: // ParentClass.js export defaul ...

Check if the input value was chosen by pressing Enter instead of clicking on it

There is an input tag with the following attributes: <input type="text" name="cOperator" class="form-control scale-input operator" placeholder="Enter your ID" autocomplete="off" onkeyup="ajax_showOptions(this,'getEmp',event)" required> ...

Tips for Making Your Popup Window Stand Out

Looking to design a unique pop-up window featuring three tree-style radio buttons and a single submit button. Upon selecting one of the radio buttons, the chosen value should be recorded in the parent window. ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Is there a way to display the specific information of a flatlist item in a pop-up window?

Welcome to the HomesScreen.js! This section handles rendering the flat list elements. import { StatusBar } from 'expo-status-bar'; import { Button, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

What is the best way to remove a specific set of IDs from a query in Meteor's MongoDB?

I'm encountering a unique challenge with my first Meteor app that I can't find a solution for through Google searches. My goal is to fetch all listings that a user has not 'liked' or 'disliked' yet. In this scenario, any user ...

Imitate network glitches

We have been utilizing the protractor tool for end-to-end testing for quite some time. Currently, we are exploring various corner cases that involve modifying the responses from API endpoint requests. To achieve this, we are utilizing protractor-http-mock ...