databasefacebook-fqlfaunadb

FaunaDB get document stored with foreign key


I've created two tables in FaunaDB, "customers" and "orders". I created an Index, to get a document by a data.transactionObj.transactionId.

So far so good, but how can I extend the query below, to get the document referenced in data.customerRef?

This query:

Map(
  Paginate(Match(Index("orders_by_trx"), "220704142800610948")),
  Lambda("x", Get(Var("x")))
)

returns

{
  data: [
    {
      ref: Ref(Collection("orders"), "336256180042072264"),
      ts: 1660641327310000,
      data: {
        customerRef: Ref(Collection("customers"), "340132521031237836"),
        transactionObj: {
          transactionId: "220704142200610948",
          status: "transmitted",
          refno: "l56pwwmiHuber",
          currency: "CHF",
          paymentMethod: "TWI",
          amount: 100
        },
        cart: {
          cards: [
            {
              id: "629f6e2f909b7c89f114a874",
              name: "MCA Couchtisch Sakura",
              verkaufspreis: 99,
              anzahl: 1,
            }
          ]
        }
      }
    }
  ]
}

Solution

  • You can compose the response as an arbitrary JSON value.

    You haven't specified what structure you need, so I'm assuming that you want something like:

    {
      order: <order document>,
      customer: <customer document>,
    }
    

    To accomplish that, here's an updated query that should work:

    Map(
      Paginate(Match(Index("orders_by_trx"), "220704142800610948")),
      Lambda(
        "order_ref",
        Let(
          {
            order: Get(Var("order_ref")),
            customer_ref: Select(["data", "customerRef"], Var("order")),
            customer: Get(Var("customer_ref")),
          },
          {
            order: Var("order"),
            customer: Var("customer")
          }
        )
      )
    )
    

    The query used the Let function to hold intermediate results and compose the response structure.

    Fauna queries can perform any number of reads and writes provided that you don't exceed the transaction limits.