9

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.

ProblemsOfSumit
  • 19,543
  • 9
  • 50
  • 61

4 Answers4

11

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

Brecht De Rooms
  • 1,802
  • 7
  • 15
4

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) ])

evbruno
  • 186
  • 1
  • 9
1

You can use the match() function to find the document whose id you need and then call the id() method on the "ref" attribute of the JSON returned. For example, say I want to get the ref id of a user on a "User" collection it'd be as follows:

user = client.query(q.get(q.match(q.index("user_by_name"), "Paul")))

This would return a JSON containing a Ref object, with the key of ["ref"], which holds the id we need. From this we can retrieve the id using the id() function as follows:

print(user["ref"].id())

Which would print the id to the console. You can of course pass this into a different query as you might want to.

kelvin
  • 1,421
  • 13
  • 28
1

According to the Doc here how you can get the id from the Ref

client.query(
  q.Let(
    {
      doc: q.Get(q.Ref(q.Collection("users"), "1")),
    },
    {
      "id": q.Select(["ref", "id"], q.Var("doc")),
    }
  )
)
Ali Hussein
  • 169
  • 1
  • 5