'Get nested document within document in FaunaDB

I'm fairly new to Fauna so please forgive me. I'd like to make one query that returns a nested document within a document. I access the initial document that contains the nested document by the index I created below:

Get(Match(Index("account-user_by_sub"), "google-oauth2|10233470761")

That index returns this:

{
  ref: Ref(Collection("account-users"), "325230990747238466"),
  ts: 1646423292780000,
  data: {
    userAccount: Ref(Collection("user-accounts"), "325134359745003585"),
    firstName: "firstName",
    lastName: "lastName",
    sub: "google-oauth2|10233470761",
  }
}

I'd like to make one query that returns the above response along with the nested userAccount document. I found similar questions on Stackoverflow but didn't have any luck with their solutions. I tried this below but it just returned the block of code you see above:

Get(Match(Index("account-user_by_sub"), "google-oauth2|10233470761")),
    Lambda("X",
    Let(
        {
             accountUserDoc: Get(Var("X")),
             userAccountRef: Get(Select(["data", "userAccount"], Var("accountUserDoc")))
        },
        {
             accountUser: Var("accountUserDoc"),
             userAccount: Get(Var("userAccountRef"))
        }
    )
)


Solution 1:[1]

The query you tried won't work: it tries to chain two FQL expressions together with a comma, and there's no connection between the two, so the Lambda doesn't receive a parameter.

You're pretty close to the solution though. Try this:

Let(
  {
    accountUserDoc: Get(
      Match(
        Index("account-user_by_sub"),
        "google-oauth2|10233470761"
      )
    ),
    userAccountDoc: Get(
      Select(["data", "userAccount"], Var("accountUserDoc"))
    )
  },
  {
    accountUser: Var("accountUserDoc"),
    userAccount: Var("userAccountDoc")
  }
)

Basically, this places the initial Get inside the Let, rather than trying to pass the document as a parameter.

Since you are calling Get on the value in the userAccount field, you didn't need to do it again when composing the desired result; that would have failed anyway because Get takes a reference, not a document.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eskwayrd