0

I am trying to implementing data-loader in my project-

Here is my code-

subCategory: async (parent, _, {loaders}) => {
    console.log(parent);
    // I try it but getting errors
    const subcategory = await loaders.subCategory.load(parent.subCategory.toString());
    return subcategory;
}

The above code's console result-

{
  _id: new ObjectId("61a658932c7ad474fde70893"),
  name: "Men's",
  createdAt: 2021-11-30T17:00:03.225Z,
  updatedAt: 2021-12-05T13:52:26.848Z,
  __v: 2,
  subCategory: [ // Array of IDS
    new ObjectId("61acc3f8a49c6cf3b04cf225"),
    new ObjectId("61acc41aa49c6cf3b04cf22b")
  ]
}
{
  _id: new ObjectId("61a65980890ef431bc0ecbcf"),
  name: 'Women',
  createdAt: 2021-11-30T17:04:00.530Z,
  updatedAt: 2021-12-05T13:54:00.449Z,
  __v: 3,
  subCategory: [ // Array of IDS
    new ObjectId("61acc460dba0e6083be97fb5"),
    new ObjectId("61acc471dba0e6083be97fbd"),
    new ObjectId("61acc478dba0e6083be97fc3")
  ]
}

I try it with this function--

module.exports.batchSubCategory = async (categoryIds) => {
    const subcategory = await Subcategory.find({_id: {$in: Ids}});
    return Ids.map(categoryId => subcategory.find(category => category.id === categoryId));
}

Here is context

context: async ({req}) => {
        return {
            loaders: {
                subCategory: new Dataloader(keys => loaders.categoryLoaders.batchSubCategory(keys))
            }
        }
},

I am using apollo server.

1 Answers1

0

I have also encountered this type of problem. The solution was to use the .loadMany() Method. You can also refer to this URL https://medium.com/the-marcy-lab-school/how-to-use-dataloader-js-9727c527efd0.

Just try Instead of .load() method:

const subcategory = await loaders.subCategory.load(parent.subCategory.toString());

Use the .loadMany() Method:

const subcategory = await loaders.subCategory.loadMany(parent.subCategory);
Don2x
  • 16
  • 1
  • 3