Query

View as Markdown

Query

A Query holds one list request for a collection of the stack, such as the entries of a content type or the global fields of a stack. Use this object to

  • list the items of a collection that match a query condition
  • read only the first matching item
  • count the matching items

Call the query method of a collection object to get a Query, for example stack.contentType('<CONTENT_TYPE_UID>').entry().query(params) or stack.globalField().query(params). query sends nothing. The request goes out when you call find, findOne or count.

Class-Level Notes

What a query contains.

  • The request path of the collection that built it, for example /content_types/{content_type_uid}/entries.
  • A copy of the params that you passed to query. The SDK sends params.query as query=<JSON> and every other key as a query parameter, with arrays in the key[]=value form.
  • A copy of the headers of the collection object, taken when you called query. A header that you add to the collection object later does not reach this query. Change the headers of the query itself with addHeader, addHeaderDict and removeHeader.

One parameter map for all three calls.

  • find, findOne and count send the same parameter map. findOne adds limit=1 to it and count adds count=true, and both values stay for every later call on the same query.
  • Call query again for each request when you mix these calls, so that each request starts from your own params.

ContentstackCollection. find and findOne resolve to a ContentstackCollection. Its properties come from the response body:

PropertyTypeAccessDefaultDescription
itemsobject[]Read[]The matching items, each one an object of the queried class, such as Entry.
countnumberReadundefinedTotal number of matching items, when the response has count.
schemaobjectReadundefinedContent type schema, when the response has schema.
content_typeobjectReadundefinedContent type details, when the response has content_type.
noticestringReadundefinedMessage from the API, when the response has notice.
  • Each object in items has the methods of a single item of its class, for example fetch, update and delete on an Entry. It carries the headers of the query.
  • count resolves to the response body as the API returns it, not to a ContentstackCollection.

Pagination.

  • Each call sends one request and reads one page. The SDK does not request the next page.
  • Pass limit and skip in the params of query to read another page. Without them the API applies its own page size.

Rate limiting and retry.

  • This SDK automatically retries on 429 with configurable delay and attempt limits.

Additional Resource For more information on the retry options and their defaults, refer to the Contentstack documentation.

Capability Matrix

CapabilitySupportedNotes / Alternative
Read every page of a collection in one callNoCall query again with a larger skip for each page
Chain filter methods such as where or limitNoPass the condition and options in the params of query
Reuse one query for count and then findNoCall query again for each request

Method Index

Send the request. Available on any Query.

Method NameReturnsDescription
findThe matching items.Lists the matching items.
findOneThe first matching item.Reads the first matching item.
countThe API response with the number of matching items.Counts the matching items.

Set request headers. Available on any Query.

Method NameReturnsDescription
addHeaderThe same query, for chaining.Adds one request header.
addHeaderDictThe same query, for chaining.Adds several request headers.
removeHeaderThe same query, for chaining.Removes one request header.

Class-Level Snippet

The snippet below lists the entries of one content type whose title matches, ten at a time, and prints the total count.

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.contentType('<CONTENT_TYPE_UID>').entry()
    .query({ query: { title: 'Hello' }, limit: 10, skip: 0, include_count: true })
    .find()
  console.log(result.count)
  for (const entry of result.items) {
    console.log(entry.uid, entry.title)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Methods

Each method of the Query class has its own section below, with its parameters, validation rules, behavior, and examples.

addHeader

addHeader adds one header to the request that this query sends.

NameTypeDescription
key (required)string

Header name, for example x-request-id.

Default: Not applicable
value (required)string

Header value to send.

Default: Not applicable

Returns: Query. The same query, for chaining.

Validation

  • There is no client-side validation. A null or undefined key leaves the headers unchanged, and addHeader returns the same query.
  • An invalid value surfaces as a rejected promise from the find, findOne or count call that follows.

Behavior

  • Client-side only. addHeader sends no request.
  • The query holds its own copy of the headers, taken when you called query. The change applies to this query only, not to the collection object that built it.
  • A key that the query already holds gets the new value.
  • The items that find and findOne return carry the headers of the query.

Example

Basic usage: tag one list request

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const query = stack.contentType('<CONTENT_TYPE_UID>').entry()
  .query({ query: { title: 'Hello' } })
  .addHeader('x-request-id', 'docs-123')
// find(), findOne() and count() on this query send the header
console.log(typeof query.find)

addHeaderDict

addHeaderDict adds several headers to the request that this query sends.

NameTypeDescription
headerDict (required)object

Header names and values to add.

Default: Not applicable

Returns: Query. The same query, for chaining.

Validation

  • There is no client-side validation. A null value, or a value that is not an object, leaves the headers unchanged, and addHeaderDict returns the same query.
  • An invalid value surfaces as a rejected promise from the find, findOne or count call that follows.

Behavior

  • Client-side only. addHeaderDict sends no request.
  • Copies every key of headerDict into the headers of this query. A key that the query already holds gets the new value.
  • The change applies to this query only, not to the collection object that built it.

Example

Basic usage: send two extra headers with one list request

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const query = stack.globalField()
  .query({ include_count: true })
  .addHeaderDict({ 'x-request-id': 'docs-123', 'x-team': 'docs' })
// find(), findOne() and count() on this query send both headers
console.log(typeof query.count)

count

count sends the query with count=true and reads the number of matching items.

This method takes no parameters.

Returns: Promise<Response>. The API response with the number of matching items.

Known issue count keeps count=true on the query, so a later find or findOne on the same query sends it too and does not return the items you expect. Call query again before you call find.

Validation

  • There is no client-side validation.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends the same GET request as find, with count=true added to the query parameters. Get all Releases describes count as returning only the total count, without the items.
  • Resolves to the response body as the API returns it. The SDK does not wrap it in a ContentstackCollection and does not read the number out of it.
  • To read the items and the total in one request, pass include_count: true to query and call find instead.

Example

Basic usage: count the entries with a given title

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.contentType('<CONTENT_TYPE_UID>').entry()
    .query({ query: { title: 'Hello' } })
    .count()
  console.log(response)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

find

find sends the query and lists the items that match it.

This method takes no parameters.

Returns: Promise<ContentstackCollection>. The matching items.

Validation

  • There is no client-side validation. find sends the params that you passed to query as they are.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends one GET request to the path of the collection that built the query, for example GET /v3/content_types/{content_type_uid}/entries, as Get all entries describes for entries.
  • Resolves to a ContentstackCollection. items holds one object of the queried class per item in the response, with the methods of a single item.
  • count holds the total when the response has it, for example when params include include_count: true.
  • Reads one page. Pass limit and skip in the params of query to read another page.
  • Sends limit=1 and count=true too when you called findOne or count on the same query before.

Example

Basic usage: list the entries of a content type

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.contentType('<CONTENT_TYPE_UID>').entry().query().find()
  for (const entry of result.items) {
    console.log(entry.uid, entry.title)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Filter and paginate: read the second page of matching entries

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.contentType('<CONTENT_TYPE_UID>').entry()
    .query({ query: { title: 'Hello' }, locale: '<LOCALE>', limit: 10, skip: 10, include_count: true })
    .find()
  console.log(`${result.items.length} of ${result.count}`)
  // Each item is an Entry with fetch, update and delete
  const first = result.items[0]
  if (first) {
    const entry = await first.fetch()
    console.log(entry.title)
  }
} catch (error) {
  console.error(error.errorMessage)
}

findOne

findOne sends the query with limit=1 and reads the first item that matches.

This method takes no parameters.

Returns: Promise<ContentstackCollection>. The first matching item.

Known issue findOne keeps limit=1 on the query, so a later find on the same query also returns one item. Call query again before you call find.

Validation

  • There is no client-side validation.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.
  • No match is not an error. The promise resolves with an empty items array.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends the same GET request as find, with limit=1 added to the query parameters.
  • Resolves to a ContentstackCollection, not to one item. Read the item at items[0].

Example

Basic usage: read the first entry with a given title

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const result = await stack.contentType('<CONTENT_TYPE_UID>').entry()
    .query({ query: { title: 'Hello' } })
    .findOne()
  const entry = result.items[0]
  console.log(entry ? entry.uid : 'No entry matches')
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

removeHeader

removeHeader removes one header from the request that this query sends.

NameTypeDescription
key (required)string

Name of the header to remove.

Default: Not applicable

Returns: Query. The same query, for chaining.

Validation

  • There is no client-side validation. A null or undefined key, or a key that the query does not hold, leaves the headers unchanged.
  • An invalid value surfaces as a rejected promise from the find, findOne or count call that follows.

Behavior

  • Client-side only. removeHeader sends no request.
  • Removes the key from the headers of this query only. The collection object that built the query keeps it.
  • The SDK adds some headers at request time, for example the authorization header of the client. removeHeader cannot remove those.

Example

Basic usage: send a list request without the branch header

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })

const query = stack.contentType().query().removeHeader('branch')
// This query reads the content types of the default branch
console.log(typeof query.find)