Fetch multiple documents by reference

Hi there,

I’d like to perform a query that retrieves any document that has a ref that is contained in an array of refs that I provide. And I’d like to do this without performing a scan of the collection.

I read this example on using an array of GETs. And is says:

This saves network bandwidth and processing by grouping several requests for data into the same operation.

Let’s say I am providing this array of refs:

const users = [
  Ref(Collection("User"), "344499104832815692"),
  Ref(Collection("User"), "344500844512674379")

And the query I’d like to run is:

const response = await this.client.query([
    Ref(Collection("User"), "344499104832815692"),
    Ref(Collection("User"), "344500844512674379"),

But since there is no knowing what the users are at any given moment, I’d like this to be dynamic, depending on what’s in the users array.

Is there any way to programmatically use the users array to create a query like the above?

I’ve trie this and other variations, but to no avail.

const gets = users.map((user) => Get(user));
const response = await this.client.query(gets);

It seems like, if this is possible, that it would be a lot more efficient that performing a search.

Any helpful advice would be very appreciated.

I’ve trie this and other variations, but to no avail.

What response did you receive? Provided that you imported the driver’s FQL functions correctly, your technique should work.

My repro doesn’t use the User collection, and since I’m running my query outside of a function, I cannot use await, but this works as expected:

const letters = [
  q.Ref(q.Collection("Letters"), "101"),
  q.Ref(q.Collection("Letters"), "102")

const gets = letters.map((letter) => q.Get(letter))
  .then(ret => console.log(ret))
  .catch(error => console.error('Error: ', error.message))

The response is:

    ref: Ref(Collection("Letters"), "101"),
    ts: 1664816322550000,
    data: { letter: 'A', extra: 'First' }
    ref: Ref(Collection("Letters"), "102"),
    ts: 1664816322550000,
    data: { letter: 'B', extra: 'second' }
1 Like

Hi @ewan,

Thanks again for another helpful response. Your confirmation that it should work caused me to dig a bit deeper to find out what I was doing wrong.

In short, the return of the query with an array of gets, returns an array of objects, rather than an object with a data array (of objects).

I’ve now handled that scenario thanks to your help! :tada:

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.