Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an ID from Ref in fauna?

Tags:

faunadb

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.

like image 546
ProblemsOfSumit Avatar asked May 26 '20 08:05

ProblemsOfSumit


2 Answers

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

like image 182
Brecht De Rooms Avatar answered Oct 20 '22 17:10

Brecht De Rooms


You can also return an array with the id and the expanded ref, with that, you are not committing to the json format (that could change in the future). You can achieve that, updating your lambda to Lambda(x => [ Select('id', x), Get(x) ])

like image 26
evbruno Avatar answered Oct 20 '22 17:10

evbruno