Search code examples
faunadb

How to get an ID from Ref in fauna?


I'm fetching documents from faunadb and I would like their ID to be in the payload that I send to the client.

This is how I fetch the documents and return their data as a collection


serverClient.query(
  q.Map(
    q.Paginate(q.Documents(q.Collection('Portfolio')), { size: 999999 }),
      q.Lambda(x => q.Get(x))
    )
  )
  .then((ret) => ret.data.map(x => ({ ...x.data, _id: x.ref })))

Now _id is a Ref. Looking like this when I log it to the console:

Ref(Collection("Portfolio"), "266565241615155713")

And like this when JSON Stringifying it:

{"@ref":{"id":"266565241615155713","collection":{"@ref":{"id":"Portfolio","collection":{"@ref":{"id":"collections"}}}}}}

I basically need to get the ID 266565241615155713 from that Ref. How can I do that? I tried x.ref['@ref'].id but @ref is undefined. The documentation did not help me here

Thanks in advance for any hints.


Solution

  • You should be able to get the id with ref.id before it's transformed to Json which I believe is the case where you are currently doing: '_id: x.ref', so just replace that with _id: x.ref.id should be fine.

    Once you have transformed it to Json, you will have to do jsonRef.['@ref'].id