How to GET a document and its ref's id

Hi,

I have a database of beer types. Carslberg, Heineken etc. The beers only have two properties: “name” and “alcohol”. So a beer document would look like

{
    "ref": Ref(Collection("beers"), id),
    "ts": ...,
    "data": {
        "name": "Carlsberg",
        "alcohol": "5,2%"
    }
}

I want to write a FQL query that fetches the content of the data field - the data object - and that includes the ref’s ID with it. Is this such a rare situation? I find almost no examples online of that. Playing around in the dashboard’s shell I managed to solve it for now like this:

Merge(
  { id: Select(
    ["ref", "id"],
    Get(Match(Index("beer_by_name"), "Carlsberg"))
  )},
  Select(
    ["data"],
    Get(Match(Index("beer_by_name"), "Carlsberg"))
  )
)

But it feels awkward and complex for such a small, normal task to do, no? What am I missing? It should be way easier shouldn’t it? Does anybody know of an easier way? My end goal is just to have my API return the beer entity with the ID included.

Thanks in advance

Well this is pretty straightforward :

Let(
  { beer: Get(Match(Index("beer_by_name"), "Carlsberg")) },
  Merge(
    Select(['data'], Var('beer')),
    { id: Select(['ref', 'id'], Var('beer')) }
  )
)

You could also create an UDF for this instead :

// get
Query(
  Lambda(
    "ref",
    Let(
      { obj: Get(Var('ref')) },
      Merge(
        Select(['data'], Var('obj')),
        { id: Select(['ref', 'id'], Var('obj')) }
      )
    )
  )
)

Then use it anytime (add privileges if needed) :

Call(Function('get'), Match(Index("beer_by_name"), "Carlsberg"))
2 Likes

Yes, that was is more straight forward. Thank you for that.

Can we conclude that one has to explicitly merge in the id field of a document then. There is no way, no built in function, that includes it out of the box?

@Andreas_B the more canonical thing to do would be to work with the whole Document, including the Ref in the client. It’s of a type that you can feed right back into another query. If you pull the id out, then you have to reconstruct the Ref (knowing the collection it came from). Basically, Documents are meant to be used as Documents. Secondarily, FQL gives you lots of tools to do other things if you need to.

For example, the GraphQL API does work with the id fields rather than refs. But if your in all-FQL land, than working with the Refs directly can be more straight forward.

Can be. All depends on how your using it, right?