mongodb - Dataloader 没有返回相同长度的数组?

标签 mongodb express mongoose graphql

我正在使用 graphql 和 mongodb (mongoose) 构建一个快速 JS 应用程序。我正在使用 facebooks Dataloader 来批处理和缓存请求。

除了这个用例,它工作得很好。

我有一个充满用户帖子的数据库。每个帖子都包含用户 ID 以供引用。当我打电话返回数据库中的所有帖子时。帖子返回正常,但如果我尝试在每个帖子中吸引用户。有多个帖子的用户将只返回一个用户,因为第二个用户的 key 已缓存。所以来自用户“x”的 2 个帖子(键)将只返回 1 个用户对象“x”。

然而,Dataloader 必须返回与其收到的 key 相同数量的 promise 。

它有一个选项可以将缓存指定为 false,这样每个键都会发出请求。但这似乎不适用于我的用例。

抱歉,如果我没有很好地解释这一点。

这是我的 graphql 请求

query {
  getAllPosts {
    _id // This is returned fine
    user {
      _id
     }
   }
 }

返回错误:
DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.

最佳答案

您是否正在尝试批量发布 key [1, 2, 3] 并期望获得用户结果 [{ user1 }, {user2}, { user1 }]

或者您是否正在尝试批处理用户 key [1, 2] 并期望获得发布结果 [{ post1}, {post3}] 和 [{ post2 }]?

似乎只有在第二种情况下,您才会遇到键的长度与结果数组的长度不同的情况。

要解决第二个问题,您可以在 sql 中执行类似的操作:

const loader = new Dataloader(userIDs => {
  const promises = userIDs.map(id => {
    return db('user_posts')
      .where('user_id', id);
  });

  return Promise.all(promises);
})

loader.load(1)
loader.load(2)

因此您返回 [[{ post1}, {post3}], [{ post2 }]] 数据加载器可以解包。

如果你这样做了:

const loader = new Dataloader(userIDs => {
  return db('user_posts')
      .where('user_id', [userIDs]);
})

loader.load(1)
loader.load(2)

您将得到 [{ post1}, {post3}, { post2 }] 并因此出现错误:该函数没有返回与以下长度相同的数组的 Promise键数组

不确定以上内容是否相关/有帮助。如果您可以提供批量加载功能的片段,我可以修改

关于mongodb - Dataloader 没有返回相同长度的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568113/

相关文章:

node.js - 简单的 Mongoose 示例不起作用

json - 如何使用expressjs通过body参数传递通用变量来更新属性

node.js - 加载后如何在 mongoose 子文档中使用 Schema 方法

mongodb - 如何从 Mongoose 模型对象中获取集合名称

node.js - MongoError : The 'cursor' option is required, 除了带有解释参数的聚合

javascript - 刷新 $http Promise 返回的数据

node.js - MongoError : server instance pool was destroyed

javascript - 使用多种变体过滤 MongoDB 集合

node.js - 使用 MEAN 堆栈进行用户注册和身份验证/授权

javascript - 在 req.body.id 中未定义(body-parser 和express 4)Nodejs