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.
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
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) ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With