# Computed fields

::: info What you'll learn
Fields whose value is worked out from other fields of the same document, such as a line total, a
quote total or a full name: stored so you can filter and sort by them, or worked out when read.
Editors see the new value while they type.

**Before this page:** [Fields](./fields).
:::

A computed field is an ordinary field with `computed`. Easy CMS works its value out with your
function on every save (or read); nobody types it, and values sent for it through the admin, REST,
GraphQL or the Local API are dropped.

```ts
const num = (v: unknown) => (typeof v === 'number' ? v : 0)

export default defineConfig({
  // …
  collections: [
    {
      slug: 'quotes',
      fields: [
        { name: 'title', type: 'text' },
        {
          name: 'items',
          type: 'array',
          fields: [
            { name: 'price', type: 'number' },
            { name: 'qty', type: 'number' },
            {
              name: 'lineTotal',
              type: 'number',
              computed: {
                mode: 'stored',
                deps: ['price', 'qty'],
                compute: ({ siblingData }) => num(siblingData.price) * num(siblingData.qty),
              },
            },
          ],
        },
        { name: 'discount', type: 'number' },
        {
          name: 'total',
          type: 'number',
          index: true,
          computed: {
            mode: 'stored',
            deps: ['items', 'discount'],
            compute: ({ data }) =>
              data.items.reduce((sum, row) => sum + num(row.lineTotal), 0) - num(data.discount),
          },
        },
      ],
    },
  ],
})
```

## Options

| Option | |
|---|---|
| `mode` | `'stored'`: worked out on every save and written to a column. Filter, sort and `index` it like any field. `'virtual'`: worked out each time it is read; no column. |
| `deps` | The fields **beside it** that the value comes from: in the document, the group, or the row. The admin works the value out again when one of them changes, and computed fields that depend on each other are worked out in that order. |
| `compute` | `({ data, siblingData, originalDoc, user, cms }) => value`, may be async. `data` is the whole document; `siblingData` the fields beside this one (the row, in an array or a block). `originalDoc` is the stored document when updating. |

Values inside rows and groups are worked out first, so a total can add up the rows' own computed
values. Returning `undefined` stores `null`.

Computed fields can be `text`, `textarea`, `number`, `boolean`, `date`, `email`, `json` or a single
`select`. They can't be `required`, have a `defaultValue`, be `localized` or `hidden`, and a virtual
one has no column to put `unique` or an `index` on. The config says so when it loads, and also
names a dependency that isn't beside the field, or two fields that depend on each other.

## Stored or virtual?

- **Stored** when you filter, sort or search by it (`where: { total: { gte: 10000 } }`), show it as
  a list column, or read it in SQL. It costs a column and the work on each save.
- **Virtual** when it only matters to whoever reads it, e.g. a display label. Filtering or sorting
  by one is refused with an error that says to make it stored.

Keep `compute` to the document's own data. It runs on every save (stored) or every read (virtual),
so calling other services there makes both slow. For a value from other collections (a customer's
order total), update it from an `afterChange` [hook](./hooks) or a [job](./jobs).

## In the admin

Computed fields show without an input. When a field in `deps` changes, the admin waits 300ms and
asks the server for the values (`POST /api/cms/<collection>/compute`, or `/<id>/compute` for a
saved document), so the total follows what the editor types, before saving. The server runs your
`compute`, the same one as on save, so what editors see is what is saved.

## After changing a formula {#recompute}

Stored values were worked out with the formula of their last save. After you add a stored field to
a collection that has documents, or change a formula, work them out again:

```bash [pm]
npx easy-cms recompute quotes
```

`easy-cms migrate:create` reminds you when a migration adds a stored computed field. `recompute`
runs in batches by id without hooks, versions or webhooks, and leaves `updatedAt` alone; see
[the CLI](./cli#recompute). From code: `await cms.recompute('quotes')`.

## Local API and REST

| | |
|---|---|
| `cms.compute(collection, id \| null, data, options?)` | The document as it would be read with `data` saved on top, every computed value worked out. Nothing is written; needs the access to update (or create) it. |
| `cms.computeGlobal(slug, data, options?)` | The same for a global. |
| `POST /api/cms/<collection>/compute`, `/<collection>/<id>/compute`, `/globals/<slug>/compute` | The same over REST: `{ doc }`. |

The types inferred from the config (what `cms.create` and `cms.update` take), the GraphQL inputs
and the MCP tools leave computed fields out of what you can send; documents you read have them.
