当父级包含 IDs 数组时如何使用 Data Loader?

How to use Data Loader when parent contain IDs array?

我正在尝试在我的项目中实现数据加载器-

这是我的代码-

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

以上代码的控制台结果-

{
  _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")
  ]
}

我用这个功能试试--

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

这是上下文

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

我正在使用 apollo 服务器。

我也遇到过这种问题。 解决方案是使用 .loadMany() 方法。 也可以参考这个URLhttps://medium.com/the-marcy-lab-school/how-to-use-dataloader-js-9727c527efd0.

试试 而不是 .load() 方法:

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

使用 .loadMany() 方法:

const subcategory = await loaders.subCategory.loadMany(parent.subCategory);