Meteor collections and Dataloader

Hi everyone

I’m using Dataloader/Apollo to batch queries. But I ran into a problem where Dataloader expect null to be returned as the result of the undefined _id in the below query but Meteor puts nothing in the array instead of the not defined documents.

   const c = await Companies.find({ '_id': { $in: ids } }).fetch();

This is the exception I get:

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

Any idea to get around this problem?

Meteor’s Collection API doesn’t return Promise. Try using this package: https://github.com/mikowals/find-async ?

1 Like

The promise isn’t really a problem. But if you do need it; use .rawCollection().

Regarding the dataloader problem. The response of a query should always be post-processed. Sorted, an fixed with nulls. There isn’t a guarantee that Mongo will return the documents in the same order as your id collection.

const ids = [1,2,3];

const companies = await Companies.rawCollection()
  .find({ _id: { $in: ids })
  .toArray();

const result = ids.map(id => companies.find(c => c._id === id) || null);
2 Likes

Thanks for your answer. I’m currently using the same approach but it appears not be always as beneficial as it has that mapping operation.

1 Like

I suggested the package so that you can largely stick with Meteor’s API without having to deal with the raw collection :slight_smile:

1 Like