docs/queries/select.mdx
By default, Payload's APIs will return all fields for a given collection or global. But, you may not need all of that data for all of your queries. Sometimes, you might want just a few fields from the response.
With the Select API, you can define exactly which fields you'd like to retrieve. This can impact the performance of your queries by affecting the load on the database and the size of the response.
To specify select in the Local API, you can use the select option in your query:
import type { Payload } from 'payload'
// Include mode - result type will only contain: id, text, group.number, and array
const getPosts = async (payload: Payload) => {
const posts = await payload.find({
collection: 'posts',
// highlight-start
select: {
text: true,
// select a specific field from group
group: {
number: true,
},
// select all fields from array
array: true,
},
// highlight-end
})
return posts
}
// Exclude mode - result type will contain all fields except: array and group.number
const getPosts = async (payload: Payload) => {
const posts = await payload.find({
collection: 'posts',
// Select everything except for array and group.number
// highlight-start
select: {
array: false,
group: {
number: false,
},
},
// highlight-end
})
return posts
}
The id field is always included in the result, regardless of your select query. If you pass an empty select object, only the id will be returned:
const post = await payload.findByID({
collection: 'posts',
id: '1',
select: {},
})
console.log(post) // { id: '1' }
To specify select in the REST API, you can use the select parameter in your query:
fetch(
// highlight-start
'https://localhost:3000/api/posts?select[color]=true&select[group][number]=true',
// highlight-end
)
.then((res) => res.json())
.then((data) => console.log(data))
To understand the syntax, you need to understand that complex URL search strings are parsed into a JSON object. This one isn't too bad, but more complex queries get unavoidably more difficult to write.
For this reason, we recommend to use the extremely helpful and ubiquitous qs-esm package to parse your JSON / object-formatted queries into query strings:
import { stringify } from 'qs-esm'
import type { Where } from 'payload'
const select: Where = {
text: true,
group: {
number: true,
},
// This query could be much more complex
// and QS would handle it beautifully
}
const getPosts = async () => {
const stringifiedQuery = stringify(
{
select, // ensure that `qs` adds the `select` property, too!
},
{ addQueryPrefix: true },
)
const response = await fetch(
`http://localhost:3000/api/posts${stringifiedQuery}`,
)
// Continue to handle the response below...
}
The defaultPopulate property allows you specify which fields to select when populating the collection from another document.
This is especially useful for links where only the slug is needed instead of the entire document.
With this feature, you can dramatically reduce the amount of JSON that is populated from Relationship or Upload fields.
For example, in your content model, you might have a Link field which links out to a different page. When you go to retrieve these links, you really only need the slug of the page.
Loading all of the page content, its related links, and everything else is going to be overkill and will bog down your Payload APIs. Instead, you can define the defaultPopulate property on your Pages collection, so that when Payload "populates" a related Page, it only selects the slug field and therefore returns significantly less JSON:
import type { CollectionConfig } from 'payload'
// The TSlug generic can be passed to have type safety for `defaultPopulate`.
// If avoided, the `defaultPopulate` type resolves to `SelectType`.
export const Pages: CollectionConfig<'pages'> = {
slug: 'pages',
// Specify `select`.
defaultPopulate: {
slug: true,
},
fields: [
{
name: 'slug',
type: 'text',
required: true,
},
],
}
<VideoDrawer id="Snqjng_w-QU" label="Watch default populate in action" drawerTitle="How to easily optimize Payload CMS requests with defaultPopulate" />
<Banner type="warning"> **Important:** When using `defaultPopulate` on a collection with [Uploads](/docs/fields/upload) enabled and you want to select the `url` field, it is important to specify `filename: true` as well, otherwise Payload will not be able to construct the correct file URL, instead returning `url: null`. </Banner>Setting defaultPopulate will enforce that each time Payload performs a "population" of a related document, only the fields specified will be queried and returned. However, you can override defaultPopulate with the populate property in the Local and REST API:
Local API:
import type { Payload } from 'payload'
const getPosts = async (payload: Payload) => {
const posts = await payload.find({
collection: 'posts',
populate: {
// Select only `text` from populated docs in the "pages" collection
// Now, no matter what the `defaultPopulate` is set to on the "pages" collection,
// it will be overridden, and the `text` field will be returned instead.
pages: {
text: true,
}, // highlight-line
},
})
return posts
}
REST API:
fetch('https://localhost:3000/api/posts?populate[pages][text]=true') // highlight-line
.then((res) => res.json())
.then((data) => console.log(data))