How to select specific fields on FaunaDB Query Language?

Viewed 696

I can't find anything about how to do this type of query in FaunaDB. I need to select only specifics fields from a document, not all fields. I can select one field using Select function, like below:

serverClient.query(
  q.Map(
    q.Paginate(q.Documents(q.Collection('products')), {
      size: 12,
    }),
    q.Lambda('X', q.Select(['data', 'title'], q.Get(q.Var('X'))))
  )
)

Forget the selectAll function, it's deprecated.

2 Answers

You can also return an object literal like this:

serverClient.query(
  q.Map(
    q.Paginate(q.Documents(q.Collection('products')), {
      size: 12,
    }),
    q.Lambda(
     'X',
     {
       title: q.Select(['data', 'title'], q.Get(q.Var('X')),
       otherField: q.Select(['data', 'other'], q.Get(q.Var('X'))
     }
    )
  )
)

Also you are missing the end and beginning quotation marks in your question at ['data, title']

One way to achieve this would be to create an index that returns the values required. For example, if using the shell:

CreateIndex({
  name: "<name of index>",
  source: Collection("products"),
  values: [
    { field: ["data", "title"] },
    { field: ["data", "<another field name>"] }
  ]
})

Then querying that index would return you the fields defined in the values of the index.

Map(
  Paginate(
    Match(Index("<name of index>"))
  ),
  Lambda("product", Var("product"))
)

Although these examples are to be used in the shell, they can easily be used in code by adding a q. in front of each built-in function.

Related