如何正确使用数据加载器加载功能?

发布于 2025-02-11 02:12:00 字数 1490 浏览 1 评论 0原文

我正在尝试使用dataloader's loadMany函数。但是我遇到了错误。我已经在许多地方搜索了许多解决方案。请帮我。

这是我的try-

loader.js(在这里我编写加载程序函数) -

//Models
const {Subcategory} = require("../Models/categoryModel");

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

然后在阿波罗上下文中 -

const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    context: async ({ req }) => {
        return {
            loaders: {
                subCategory: new Dataloader(keys => loaders.subCategoryLoaders.batchSubCategory(keys)),
            }
        }
    }
});

我调用此子类别loader-

subCategory: async (parent, _, { loaders }) => {
    const subcategory = await loaders.subCategory.loadMany(parent.subCategory.toString())
    return subcategory;
}

请注意:我使用loadMany,因为这里的子类别是[ ID]。这是image-

“在此处输入图像描述”

并且当我运行应用程序时 - 我将获得此类型的错误

- loader.loadmany()函数必须使用数组< key>但GoT:62BAB157E769A7DDA09EC63F,62BAB15CE769A7DDA09EC64A,62BAB164E769A7DDA09EC657。

现在我无法理解如何解决此错误。请帮我。请给您一些宝贵的时间来解决我的问题。

I am trying to use dataloader's loadMany function. But I am getting error. I already search many where but not getting any solutions. Please help me.

Here is my try-

loader.js (Here I write Loader function)-

//Models
const {Subcategory} = require("../Models/categoryModel");

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

And then in Apollo Context-

const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    context: async ({ req }) => {
        return {
            loaders: {
                subCategory: new Dataloader(keys => loaders.subCategoryLoaders.batchSubCategory(keys)),
            }
        }
    }
});

The I call this Subcategory loader-

subCategory: async (parent, _, { loaders }) => {
    const subcategory = await loaders.subCategory.loadMany(parent.subCategory.toString())
    return subcategory;
}

Notice: Here I use loadMany because Here subCategory is a Array of [ids]. Here is image-

enter image description here

And When I run the application- I am getting this type of error-

The loader.loadMany() function must be called with Array<key> but got: 62bab157e769a7dda09ec63f,62bab15ce769a7dda09ec64a,62bab164e769a7dda09ec657.

Now I can't understand How can I solve this error. Please help me. Please give some of your valuable times to solve my problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文