Hanzo
ProjectsHanzoaiCmsQueries

Depth

Documents in Payload can have relationships to other Documents. This is true for both Collections as well as Globals. When you query a Document, you can specify the depth at which to populate any of its related Documents either as full objects, or only their IDs.

Since Documents can be infinitely nested or recursively related, it's important to be able to control how deep your API populates. Depth can impact the performance of your queries by affecting the load on the database and the size of the response.

For example, when you specify a depth of 0, the API response might look like this:

{
  "id": "5ae8f9bde69e394e717c8832",
  "title": "This is a great post",
  "author": "5f7dd05cd50d4005f8bcab17"
}

But with a depth of 1, the response might look like this:

{
  "id": "5ae8f9bde69e394e717c8832",
  "title": "This is a great post",
  "author": {
    "id": "5f7dd05cd50d4005f8bcab17",
    "name": "John Doe"
  }
}

Important: Depth has no effect in the GraphQL API, because there, depth is based on the shape of your queries.

Local API

To specify depth in the Local API, you can use the depth option in your query:

import type { Payload } from @hanzo/cms'from 

const getPosts = async (payload: Payload) => {
  const posts = await payload.find({
    collection: 'posts',
    // highlight-start
    depth: 2,
    // highlight-end
  })

  return posts
}

Reminder: This is the same for Globals using the findGlobal operation.

REST API

To specify depth in the REST API, you can use the depth parameter in your query:

// highlight-start
fetch('https://localhost:3000/api/posts?depth=2')
  // highlight-end
  .then((res) => res.json())
  .then((data) => console.log(data))

Reminder: This is the same for Globals using the /api/globals endpoint.

Default Depth

If no depth is specified in the request, Payload will use its default depth for all requests. By default, this is set to 2.

To change the default depth on the application level, you can use the defaultDepth option in your root Payload config:

import { buildConfig } from @hanzo/cms'from 

export default buildConfig({
  // ...
  // highlight-start
  defaultDepth: 1,
  // highlight-end
  // ...
})

Max Depth

Fields like the Relationship Field or the Upload Field can also set a maximum depth. If exceeded, this will limit the population depth regardless of what the depth might be on the request.

To set a max depth for a field, use the maxDepth property in your field configuration:

{
  slug: 'posts',
  fields: [
    {
      name: 'author',
      type: 'relationship',
      relationTo: 'users',
      // highlight-start
      maxDepth: 2,
      // highlight-end
    }
  ]
}

How is this guide?

Last updated on

On this page