Search code examples
faunadb

how to join collections in faunadb?


I want to get nested ref's value within the query I'm executing, but by default response is returning the ref of other collection. consider this minimum example; here are user and coin models, within "users" and "coins" collections

user {     // ref: 123456
  name: foo
  location: bar
}
coin {     // ref: 124457
  amount: 5457
  awardedTo: Ref(Collection("users"), "123456")
}

when I run this query

q.Get(q.Ref(q.Collection("coins"), "124457"))

the response is something like this:

{
  data: {
    amount: 5457,
    awardedTo: @ref: {id: "123456", collection: {…}}
  },
  ref: @ref: {id: "124457", collection: {…}},
  ts: 1622547855525255
}

But how is it possible to get nested user's value in the same query to have a response like this:

{
  data: {
    amount: 5457,
    awardedTo: {
      name: foo,
      location: bar
    }
  },
  ref: @ref: {id: "124457", collection: {…}},
  ts: 1622547855525255
}

I have read Join's documentation but it wasn't helpful in this case, and also tried this way, but it didn't work either:

q.Let({
  coin: q.Get(q.Ref(q.Collection("coins"), '124457'))
},
  q.Union(
    q.Get(q.Select(["data","awaredTo"], q.Var("coin"))),
    q.Var("coins")
  )
)

Solution

  • you can use this FQL:

    Let(
      {
        coin: Select(['data'],Get(Ref(Collection("coin"), "1"))),
        user: Select(['data'],Get(Select(['awardedTo'],Var('coin'))))
      },
      Merge(Var('coin'),{awardedTo:Var('user')})
    )
    

    It retrieves data from coin, extracts the user ref and merge all together.

    Luigi