> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

# entities

***

## Overview

Entities module for managing app data.

This module provides dynamic access to all entities in the app.
Each entity gets a handler with full CRUD operations and additional utility methods.

Entities are accessed dynamically using the pattern:
`base44.entities.EntityName.method()`

This module is available to use with a client in all authentication modes:

* **Anonymous or User authentication** (`base44.entities`): Access is scoped to the current user's permissions. Anonymous users can only access public entities, while authenticated users can access entities they have permission to view or modify.
* **Service role authentication** (`base44.asServiceRole.entities`): Operations bypass entity access rules and field-level security entirely. Can read and write any record in any entity.

### Entity Handlers

An entity handler is the object you get when you access an entity through `base44.entities.EntityName`. Every entity in your app automatically gets a handler with CRUD methods for managing records.

For example, `base44.entities.Task` is an entity handler for Task records, and `base44.entities.User` is an entity handler for User records. Each handler provides methods like `list()`, `create()`, `update()`, and `delete()`.

You don't need to instantiate or import entity handlers. They're automatically available for every entity you create in your app.

### Built-in User Entity

Every app includes a built-in `User` entity that stores user account information. This entity has special security rules that can't be changed.

Regular users can only read and update their own user record. With service role authentication, you can read and update any user, and remove any user except the app owner. A removed user moves to **Recently deleted** for 30 days, where an app editor can restore them, and is then deleted permanently. You can't create users using the entities module. Instead, use the functions of the [auth module](https://docs.base44.com/hu/developers/references/sdk/docs/interfaces/auth.md) to invite or register new users.

### Generated Types

If you're working in a TypeScript project, you can generate types from your entity schemas to get autocomplete and type checking on all entity methods. See the [Dynamic Types](https://docs.base44.com/developers/references/sdk/getting-started/dynamic-types.md) guide to get started.

#### Examples

```typescript Get all records from the MyEntity entity theme={null}
// Get all records the current user has permissions to view
const myRecords = await base44.entities.MyEntity.list();
```

```typescript List every user, bypassing the User entity's access rules theme={null}
const allUsers = await base44.asServiceRole.entities.User.list();
```

## Entity Handler Methods

### get()

> **get**(`id`): `Promise`\<`T`>

Gets a single record by ID.

Retrieves a specific record using its unique identifier.

#### Parameters

**id** `string` *required*

The unique identifier of the record.

#### Returns

`Promise<T>`

Promise resolving to the record.

#### Example

```typescript Get record by ID theme={null}
const record = await base44.entities.MyEntity.get('entity-123');
console.log(record.name);
```

***

Entity handler providing CRUD operations for a specific entity type.

Each entity in the app gets a handler with these methods for managing data.

### list()

The `list()` method has three forms:

* [**Records (cursor)**](#list-records-cursor): Returns one cursor page of records. Use this for loops, or any time you want pagination that's unaffected by records added or deleted mid-walk.
* [**Distinct values (cursor)**](#list-distinct-values-cursor): Returns one cursor page of a single field's distinct values, always in ascending order. Use it to list the unique values of a field, for example to populate filter options or autocomplete.
* [**Records (skip)**](#list-records-skip): Returns an array of records. Kept for existing code. Prefer a cursor for pagination instead.

**Records (cursor)**

> **list**\<`K extends keyof T`>(`options`): `Promise`\<`EntityPage`\<`Pick`\<`T`, `K`>>>

Lists one cursor page of records, sorted and optionally field-selected.

Pass `cursor` from the previous page's `next_cursor` to keep paging, or omit it
for the first page. Records added or deleted between pages never shift the boundary.

#### Parameters

**options** `EntityListOptions\<T, K\>` *required*

Paging options.

> [accordion] Properties
>
> **sort** `SortField\<T\>`
>
> A [`SortField<T>`](#sortfield) specifying sort order, such as `'-priority'` for descending. Defaults to `'-created_date'`.
>
> **limit** `number`
>
> Maximum number of records per page, up to 5,000. Defaults to 100.
>
> **cursor** `string | null`
>
> The `next_cursor` from the previous page. Omit or pass `null` for the first page.
>
> The token carries this walk's parameters, so a later page needs only
> `cursor` and `limit`. Passing different parameters with a cursor is an error.
>
> **fields** `(keyof T)[]`
>
> Array of field names to include in each record. Defaults to all fields.

#### Returns

`EntityPage`

Promise resolving to a page of records.

> [accordion] Properties
>
> **items** `T[]` *required*
>
> The page's items. Without `distinct`, these are records in the requested sort order. With `distinct`, these are that field's distinct values instead of records, in ascending order.
>
> **next\_cursor** `string | null` *required*
>
> A cursor for the next page, or `null` on the last page. Pass it as `cursor` to keep paging.
>
> **has\_more** `boolean` *required*
>
> Whether records remain after this page.

#### Examples

```typescript Get one page of records theme={null}
const page = await base44.entities.MyEntity.list({ limit: 10 });
console.log(page.items);
```

```typescript Sort records theme={null}
const page = await base44.entities.MyEntity.list({ sort: '-priority', limit: 10 });
```

```typescript Only return specific fields theme={null}
const page = await base44.entities.MyEntity.list({ fields: ['name', 'status'], limit: 10 });
```

```typescript Walk every record with a cursor theme={null}
const allItems = [];
let page = await base44.entities.MyEntity.list({ sort: '-created_date', limit: 1000 });
allItems.push(...page.items);
while (page.has_more) {
  page = await base44.entities.MyEntity.list({ cursor: page.next_cursor, limit: 1000 });
  allItems.push(...page.items);
}
```

**Distinct values (cursor)**

> **list**\<`K extends keyof T`>(`options`): `Promise`\<`EntityPage`\<`T`\[`K`]>>

Lists one cursor page of a single field's distinct values, instead of records.

#### Parameters

**options** `EntityDistinctOptions\<T, K\>` *required*

Paging options naming the field to read.

> [accordion] Properties
>
> **distinct** `K` *required*
>
> Field whose distinct values to return, in ascending order. For an array field like `tags`, this returns the distinct individual tags used across records, not the distinct arrays.
>
> **limit** `number`
>
> Maximum number of values per page, up to 1,000. Defaults to 100.
>
> **cursor** `string | null`
>
> The `next_cursor` from the previous page. Omit or pass `null` for the first page. The token carries this lookup's parameters.

#### Returns

`EntityPage`

Promise resolving to a page of distinct values.

> [accordion] Properties
>
> **items** `T[]` *required*
>
> The page's items. Without `distinct`, these are records in the requested sort order. With `distinct`, these are that field's distinct values instead of records, in ascending order.
>
> **next\_cursor** `string | null` *required*
>
> A cursor for the next page, or `null` on the last page. Pass it as `cursor` to keep paging.
>
> **has\_more** `boolean` *required*
>
> Whether records remain after this page.

#### Examples

```typescript Regular field theme={null}
const { items: categories } = await base44.entities.Product.list({ distinct: 'category' });
// categories: ['books', 'electronics', 'toys']
```

```typescript Array field theme={null}
// Each tag counts once, not each array
const { items: tags } = await base44.entities.Product.list({ distinct: 'tags' });
// tags: ['bestseller', 'clearance', 'new']
```

**Records (skip)**

> **list**\<`K extends keyof T`>(\
> `sort?`,\
> `limit?`,\
> `skip?`,\
> `fields?`\
> ): `Promise`\<`Pick`\<`T`, `K`>\[]>

Lists records as an array, using `skip` for pagination.

Kept for existing code. Prefer a cursor for pagination instead.

#### Parameters

> [accordion] Properties
>
> **sort** `SortField\<T\>`
>
> A [`SortField<T>`](#sortfield) specifying sort order, such as `'-priority'` for descending. Defaults to `'-created_date'`.
>
> **limit** `number`
>
> Maximum number of results to return. Defaults to `5000`.
>
> **skip** `number`
>
> Number of results to skip for pagination. Defaults to `0`. Prefer a cursor for loops instead.
>
> **fields** `(keyof T)[]`
>
> Array of field names to include in the response. Defaults to all fields.

#### Returns

`Promise`\<`Pick`\<`T`, `K`>\[]>

Promise resolving to an array of records with selected fields.

#### Examples

```typescript Get all records theme={null}
const records = await base44.entities.MyEntity.list();
```

```typescript Get first 10 records sorted by date theme={null}
const recentRecords = await base44.entities.MyEntity.list('-created_date', 10);
```

```typescript Get paginated results theme={null}
// Skip first 20, get next 10
const page3 = await base44.entities.MyEntity.list('-created_date', 10, 20);
```

```typescript Get only specific fields theme={null}
const fields = await base44.entities.MyEntity.list('-created_date', 10, 0, ['name', 'status']);
```

***

### filter()

The `filter()` method has three forms. The query is always the first argument.

* [**Records (cursor)**](#filter-records-cursor): Returns one cursor page of matching records. Use this for loops, or any time you want pagination that's unaffected by records added or deleted mid-walk.
* [**Distinct values (cursor)**](#filter-distinct-values-cursor): Returns one cursor page of a single field's distinct values among matching records, always in ascending order. Use it to list the unique values of a field among matching records, for example to populate filter options or autocomplete.
* [**Records (skip)**](#filter-records-skip): Returns an array of matching records. Kept for existing code. Prefer a cursor for pagination instead.

**Records (cursor)**

> **filter**\<`K extends keyof T`>(`query`, `options`): `Promise`\<`EntityPage`\<`Pick`\<`T`, `K`>>>

Filters and returns one cursor page of matching records, sorted and
optionally field-selected.

Pass `cursor` from the previous page's `next_cursor` to keep paging, or omit it
for the first page. Records added or deleted between pages never shift the boundary.

#### Parameters

> [accordion] Properties
>
> **query** `EntityFilterQuery\<T\>` *required*
>
> Query matching [`EntityFilterQuery`](#entityfilterquery). Field names are
> case-sensitive, and records matching every field are returned.
>
> **options** `EntityListOptions\<T, K\>` *required*
>
> Paging options.
>
> > [accordion] Properties
> >
> > **sort** `SortField\<T\>`
> >
> > A [`SortField<T>`](#sortfield) specifying sort order, such as `'-priority'` for descending. Defaults to `'-created_date'`.
> >
> > **limit** `number`
> >
> > Maximum number of records per page, up to 5,000. Defaults to 100.
> >
> > **cursor** `string | null`
> >
> > The `next_cursor` from the previous page. Omit or pass `null` for the first page.
> >
> > The token carries this walk's parameters, so a later page needs only
> > `cursor` and `limit`. Passing different parameters with a cursor is an error.
> >
> > **fields** `(keyof T)[]`
> >
> > Array of field names to include in each record. Defaults to all fields.

#### Returns

`EntityPage`

Promise resolving to a page of matching records.

> [accordion] Properties
>
> **items** `T[]` *required*
>
> The page's items. Without `distinct`, these are records in the requested sort order. With `distinct`, these are that field's distinct values instead of records, in ascending order.
>
> **next\_cursor** `string | null` *required*
>
> A cursor for the next page, or `null` on the last page. Pass it as `cursor` to keep paging.
>
> **has\_more** `boolean` *required*
>
> Whether records remain after this page.

#### Examples

```typescript Get one page of matching records theme={null}
const page = await base44.entities.Order.filter({ status: 'open' }, { limit: 10 });
console.log(page.items);
```

```typescript Sort matching records theme={null}
const page = await base44.entities.Order.filter({ status: 'open' }, { sort: '-priority', limit: 10 });
```

```typescript Only return specific fields theme={null}
const page = await base44.entities.Order.filter({ status: 'open' }, { fields: ['status', 'region'], limit: 10 });
```

```typescript Walk all matching records with a cursor theme={null}
const allOrders = [];
let page = await base44.entities.Order.filter(
  { status: 'open' },
  { sort: '-created_date', limit: 1000 }
);
allOrders.push(...page.items);
while (page.has_more) {
  page = await base44.entities.Order.filter({ status: 'open' }, { cursor: page.next_cursor, limit: 1000 });
  allOrders.push(...page.items);
}
```

**Distinct values (cursor)**

> **filter**\<`K extends keyof T`>(`query`, `options`): `Promise`\<`EntityPage`\<`T`\[`K`]>>

Filters and returns one cursor page of a single field's distinct values
among matching records.

#### Parameters

> [accordion] Properties
>
> **query** `EntityFilterQuery\<T\>` *required*
>
> Query matching [`EntityFilterQuery`](#entityfilterquery). Field names are
> case-sensitive, and records matching every field are returned.
>
> **options** `EntityDistinctOptions\<T, K\>` *required*
>
> Paging options naming the field to read.
>
> > [accordion] Properties
> >
> > **distinct** `K` *required*
> >
> > Field whose distinct values to return, in ascending order. For an array field like `tags`, this returns the distinct individual tags used across records, not the distinct arrays.
> >
> > **limit** `number`
> >
> > Maximum number of values per page, up to 1,000. Defaults to 100.
> >
> > **cursor** `string | null`
> >
> > The `next_cursor` from the previous page. Omit or pass `null` for the first page. The token carries this lookup's parameters.

#### Returns

`EntityPage`

Promise resolving to a page of distinct values.

> [accordion] Properties
>
> **items** `T[]` *required*
>
> The page's items. Without `distinct`, these are records in the requested sort order. With `distinct`, these are that field's distinct values instead of records, in ascending order.
>
> **next\_cursor** `string | null` *required*
>
> A cursor for the next page, or `null` on the last page. Pass it as `cursor` to keep paging.
>
> **has\_more** `boolean` *required*
>
> Whether records remain after this page.

#### Examples

```typescript Regular field theme={null}
const { items: regions } = await base44.entities.Order.filter(
  { status: 'open' },
  { distinct: 'region' }
);
// regions: ['east', 'north', 'west']
```

```typescript Array field theme={null}
// Each tag counts once, not each array
const { items: tags } = await base44.entities.Order.filter(
  { status: 'open' },
  { distinct: 'tags' }
);
// tags: ['gift', 'international', 'rush']
```

**Records (skip)**

> **filter**\<`K extends keyof T`>(\
> `query`,\
> `sort?`,\
> `limit?`,\
> `skip?`,\
> `fields?`\
> ): `Promise`\<`Pick`\<`T`, `K`>\[]>

Filters records as an array, using `skip` for pagination.

Kept for existing code. Prefer a cursor for pagination instead.

#### Parameters

> [accordion] Properties
>
> **query** `EntityFilterQuery\<T\>` *required*
>
> Query matching [`EntityFilterQuery`](#entityfilterquery). Field names are
> case-sensitive, and records matching every field are returned.
>
> **sort** `SortField\<T\>`
>
> A [`SortField<T>`](#sortfield) specifying sort order, such as `'-priority'` for descending. Defaults to `'-created_date'`.
>
> **limit** `number`
>
> Maximum number of results to return. Defaults to `5000`.
>
> **skip** `number`
>
> Number of results to skip for pagination. Defaults to `0`. Prefer a cursor for loops instead.
>
> **fields** `(keyof T)[]`
>
> Array of field names to include in the response. Defaults to all fields.

#### Returns

`Promise`\<`Pick`\<`T`, `K`>\[]>

Promise resolving to an array of filtered records with selected fields.

#### Examples

```typescript Filter by single field theme={null}
const activeRecords = await base44.entities.MyEntity.filter({
  status: 'active'
});
```

```typescript Filter by multiple fields theme={null}
const filteredRecords = await base44.entities.MyEntity.filter({
  priority: 'high',
  status: 'active'
});
```

```typescript Filter by any matching value theme={null}
const records = await base44.entities.MyEntity.filter({
  external_id: ['item-1', 'item-2']
});
```

```typescript Filter with query operators theme={null}
const popularRecords = await base44.entities.MyEntity.filter({
  count: { $gte: 100 },
  external_id: { $in: ['item-1', 'item-2'] }
});
```

```typescript Filter with logical operators theme={null}
const records = await base44.entities.MyEntity.filter({
  $or: [
    { name: 'Example item' },
    { slug: 'example-item' }
  ]
});
```

```typescript Filter null values theme={null}
const recordsWithoutDescription = await base44.entities.MyEntity.filter({
  description: null
});
```

```typescript Filter with sorting and pagination theme={null}
const results = await base44.entities.MyEntity.filter(
  { status: 'active' },
  '-created_date',
  20,
  0
);
```

```typescript Filter with specific fields theme={null}
const fields = await base44.entities.MyEntity.filter(
  { priority: 'high' },
  '-created_date',
  10,
  0,
  ['name', 'priority']
);
```

***

### count()

> **count**(`query?`): `Promise`\<`number`>

Counts the records that match a query.

Returns the number of records the current user can read, without fetching them.
Use it for totals, badges and "page N of M".

#### Parameters

**query** `EntityFilterQuery\<T\>`

Query matching [`EntityFilterQuery`](#entityfilterquery). Defaults to all records.

#### Returns

`Promise<number>`

Promise resolving to the number of matching records.

#### Examples

```typescript Count matching records theme={null}
const open = await base44.entities.Task.count({ status: 'open' });
```

```typescript Count all records theme={null}
const total = await base44.entities.Task.count();
```

```typescript Page N of M theme={null}
const pageSize = 20;
const total = await base44.entities.Task.count({ status: 'open' });
const totalPages = Math.ceil(total / pageSize);
```

***

### aggregate()

> **aggregate**(`spec`): `Promise`\<`EntityAggregateResult`>

Computes counts, sums, averages, minimums, maximums or distinct counts, grouped by fields.

Use it for dashboards, leaderboards and reports instead of loading every record
and adding up in the browser. The server groups the records you can read and
returns one row per group, up to 1,000 rows.

#### Parameters

**spec** `EntityAggregateSpec\<T\>` *required*

What to group by and what to compute.

> [accordion] Properties
>
> **query** `EntityFilterQuery\<T\>`
>
> Filter applied before grouping, matching [`EntityFilterQuery`](#entityfilterquery). Defaults to all records.
>
> **groupBy** `(keyof T & string) | (keyof T & string)[]`
>
> Field, or up to four fields, to group by. Omit to get one total row.
>
> **dateBucket** `EntityDateBucket\<T\>`
>
> Group by a time bucket of a date field.
>
> > [accordion] Properties
> >
> > **field** `keyof T & string` *required*
> >
> > The date field to bucket by: `created_date`, `updated_date`, or a date field of your schema.
> >
> > **unit** `"day" | "week" | "month" | "year"` *required*
> >
> > Every date field supports `day`, `month` and `year`. The `created_date` and `updated_date` fields also support `week`.
>
> **count** `boolean`
>
> Whether to include the number of records per group as `count`. Defaults to `true`.
>
> **sum** `(keyof T & string) | (keyof T & string)[]`
>
> Field, or fields, to sum. Each appears in the rows as `sum_<field>`.
>
> **avg** `(keyof T & string) | (keyof T & string)[]`
>
> Field, or fields, to average. Each appears in the rows as `avg_<field>`.
>
> **min** `(keyof T & string) | (keyof T & string)[]`
>
> Field, or fields, to take the minimum of. Each appears in the rows as `min_<field>`.
>
> **max** `(keyof T & string) | (keyof T & string)[]`
>
> Field, or fields, to take the maximum of. Each appears in the rows as `max_<field>`.
>
> **countDistinct** `keyof T & string`
>
> Field whose distinct values to count per group, returned as `count_distinct_<field>`. Unlike `distinct` on `list()`/`filter()`, an array field here counts each whole array as one value, not its individual elements.
>
> **having** `Record\<string, any\>`
>
> Filter applied to the computed fields after grouping, not to raw or `groupBy` fields. Supports `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, and `$nin`. With more than one key, a row is kept only when every key's condition holds. For example, grouped by `external_id`, `having: { count: { $gt: 1 } }` keeps only the external ids that appear in more than one record.
>
> **sort** `string`
>
> Computed or group field to sort the rows by, with a `-` prefix for descending. For example `'-count'`.
>
> **limit** `number`
>
> Maximum number of rows, up to 1,000. Defaults to 1,000.

#### Returns

`EntityAggregateResult`

Promise resolving to the rows and a `truncated` flag.

> [accordion] Properties
>
> **rows** `Record\<string, any\>[]` *required*
>
> One row per group. Each row has the group fields by name, then `count`, `sum_<field>`, `avg_<field>`, `min_<field>`, `max_<field>` or `count_distinct_<field>`.
>
> **truncated** `boolean` *required*
>
> Set to `true` when more groups exist than `limit` allowed.

#### Examples

```typescript Sales per agent this month, biggest first theme={null}
const { rows } = await base44.entities.Sale.aggregate({
  query: { sale_date: { $gte: '2026-09-01' } },
  groupBy: 'agent_id',
  sum: 'amount',
  sort: '-sum_amount'
});
// rows: [
//   { agent_id: 'a1', count: 42, sum_amount: 18250 },
//   { agent_id: 'a2', count: 37, sum_amount: 15400 },
//   ...
// ]
```

```typescript Tasks created per day theme={null}
const { rows } = await base44.entities.Task.aggregate({
  dateBucket: { field: 'created_date', unit: 'day' }
});
// rows: [
//   { created_date: '2026-09-01', count: 8 },
//   { created_date: '2026-09-02', count: 11 },
//   ...
// ]
```

```typescript Find duplicated external ids theme={null}
const { rows } = await base44.entities.Order.aggregate({
  groupBy: 'external_id',
  having: { count: { $gt: 1 } }
});
// rows: [
//   { external_id: 'ext-42', count: 3 },
//   { external_id: 'ext-77', count: 2 }
// ]
```

```typescript Unique customers per product theme={null}
const { rows } = await base44.entities.Order.aggregate({
  groupBy: 'product_id',
  countDistinct: 'customer_id'
});
// rows: [
//   { product_id: 'p1', count_distinct_customer_id: 86 },
//   { product_id: 'p2', count_distinct_customer_id: 34 }
// ]
```

***

### create()

> **create**(`data`): `Promise`\<`T`>

Creates a new record.

Creates a new record with the provided data.

#### Parameters

**data** `Partial\<T\>` *required*

Object containing the record data.

#### Returns

`Promise<T>`

Promise resolving to the created record.

#### Example

```typescript Create a new record theme={null}
const newRecord = await base44.entities.MyEntity.create({
  name: 'My Item',
  status: 'active',
  priority: 'high'
});
console.log('Created record with ID:', newRecord.id);
```

***

### bulkCreate()

> **bulkCreate**(`data`): `Promise`\<`T`\[]>

Creates multiple records in a single request.

Efficiently creates multiple records at once. This is faster
than creating them individually.

This isn't a transaction. Each record is written on its own, so if the call
fails partway, the records already written stay written. Learn more about
[concurrent updates](https://docs.base44.com/developers/backend/resources/entities/entity-schemas.md#concurrent-updates).

#### Parameters

**data** `Partial\<T\>[]` *required*

Array of record data objects.

#### Returns

`Promise<T[]>`

Promise resolving to an array of created records.

#### Example

```typescript Create multiple records at once theme={null}
const result = await base44.entities.MyEntity.bulkCreate([
  { name: 'Item 1', status: 'active' },
  { name: 'Item 2', status: 'active' },
  { name: 'Item 3', status: 'completed' }
]);
```

***

### importEntities()

> **importEntities**(`file`): `Promise`\<`ImportResult`\<`T`>>

Imports records from a file.

Imports records from a file, typically CSV or similar format.
The file format should match your entity structure. Requires a browser environment and can't be used in the backend.

#### Parameters

**file** `File` *required*

File object to import.

#### Returns

`ImportResult<T>`

Promise resolving to the import result containing status, details, and created records.

> [accordion] Properties
>
> **status** `"error" | "success"` *required*
>
> Status of the import operation.
>
> **details** `string | null` *required*
>
> Details message, e.g., "Successfully imported 3 entities with RLS enforcement".
>
> **output** `T[] | null` *required*
>
> Array of created entity objects when successful, or null on error.

#### Example

```typescript Import records from file in React theme={null}
const handleFileImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
  const file = event.target.files?.[0];
  if (file) {
    const result = await base44.entities.MyEntity.importEntities(file);
    if (result.status === 'success' && result.output) {
      console.log(`Imported ${result.output.length} records`);
    }
  }
};
```

***

### upsert()

> **upsert**(`records`, `options`): `Promise`\<`EntityUpsertResult`\<`T`>>

Creates or updates records by a key you define, instead of by `id`.

Use this whenever records have a natural key, such as an ID from another system or a
one-per-user record keyed by `user_id`, so you don't have to look up each record first
to decide between create and update. Name the field, or fields, that identify a record,
and the server updates the records whose key already exists and creates the rest, in
one call.

You can upsert up to 500 records per request. When two records in one call share a
key, the last one wins. Updates merge the given fields into the existing record, like
[`update()`](#update).

This isn't a transaction. Each record is written on its own, so if the call
fails partway, the records already written stay written. Concurrent calls with
the same key can also create duplicate records. Learn more about
[concurrent updates](https://docs.base44.com/developers/backend/resources/entities/entity-schemas.md#concurrent-updates).

#### Parameters

> [accordion] Properties
>
> **records** `Partial\<T\>[]` *required*
>
> Array of record data objects. Each must carry a value, not an object or
> array, for every field named in `options.key`, to find or create by. Other fields are
> optional, and only the ones you include are merged into a matched record, like `update()`.
>
> **options** `EntityUpsertOptions\<T\>` *required*
>
> The key field or fields.
>
> > [accordion] Properties
> >
> > **key** `(keyof T & string) | (keyof T & string)[]` *required*
> >
> > Field, or fields, that identify a record. A record whose key values match an existing record updates it, and any other record is created.

#### Returns

`EntityUpsertResult`

Promise resolving to the counts and the written records.

> [accordion] Properties
>
> **created** `number` *required*
>
> Number of records that were created.
>
> **updated** `number` *required*
>
> Number of existing records that were updated.
>
> **records** `T[]` *required*
>
> The written records, created and updated, as they now exist.

#### Examples

```typescript Sync by sku theme={null}
const result = await base44.entities.Product.upsert(
  supplierCatalog.map(p => ({ sku: p.sku, name: p.name, price: p.price })),
  { key: 'sku' }
);
console.log(`${result.created} new, ${result.updated} updated`);
```

```typescript Compound key theme={null}
const result = await base44.entities.Inventory.upsert(
  warehouseFeed.map(row => ({ sku: row.sku, warehouse: row.warehouseCode, quantity: row.qty })),
  { key: ['sku', 'warehouse'] }
);
console.log(`${result.created} new, ${result.updated} updated`);
```

***

### update()

> **update**(`id`, `data`): `Promise`\<`T`>

Updates an existing record.

Updates a record by ID with the provided data. Only the fields
included in the data object will be updated.

To update a single record by ID, use this method. To apply the same
update to many records matching a query, use [`updateMany()`](#updatemany).
To update multiple specific records with different data each, use
[`bulkUpdate()`](#bulkupdate).

#### Parameters

> [accordion] Properties
>
> **id** `string` *required*
>
> The unique identifier of the record to update.
>
> **data** `Partial\<T\>` *required*
>
> Object containing the fields to update.

#### Returns

`Promise<T>`

Promise resolving to the updated record.

#### Examples

```typescript Update single field theme={null}
const updated = await base44.entities.MyEntity.update('entity-123', {
  status: 'completed'
});
```

```typescript Update multiple fields theme={null}
const updated = await base44.entities.MyEntity.update('entity-123', {
  name: 'Updated name',
  priority: 'low',
  status: 'active'
});
```

***

### updateMany()

> **updateMany**(`query`, `data`): `Promise`\<`UpdateManyResult`>

Applies the same update to all records that match a query.

Use this when you need to make the same change across all records that
match specific criteria. For example, you could set every completed order
to "archived", or increment a counter on all active users.

Results are batched in groups of up to 500. When `has_more` is `true`
in the response, call `updateMany` again with the same query to update
the next batch. Make sure the query excludes already-updated records
so you don't re-process the same entities on each iteration. For
example, filter by `status: 'pending'` when setting status to `'processed'`.

Each matching record is updated on its own, and the call isn't a transaction.
All the update operators in a call, such as `$set`, `$inc`, and `$push`, are
applied to each record in a single write.
To claim one record safely, so that only one of 2 users acting at the same
time succeeds, pass that record's `id` as a plain value plus the conditions
that must still be true, then check `updated` in the response. The conditions
are only checked again at write time when the query names a single `id`. Any
other query, including several IDs in `$in` or `$or`, finds the matching
records first and then updates them. Learn more about
[concurrent updates](https://docs.base44.com/developers/backend/resources/entities/entity-schemas.md#concurrent-updates).

To update a single record by ID, use [`update()`](#update) instead. To update
multiple specific records with different data each, use [`bulkUpdate()`](#bulkupdate).

#### Parameters

> [accordion] Properties
>
> **query** `Partial\<T\>` *required*
>
> Query matching [`EntityFilterQuery`](#entityfilterquery), selecting which records to update.
>
> **data** `Record\<string, Record\<string, any\>\>` *required*
>
> Update operation object containing one or more
> [MongoDB update operators](https://www.mongodb.com/docs/manual/reference/operator/update/).
> Each field may only appear in one operator per call.
> Supported update operators include `$set`, `$rename`, `$unset`, `$inc`, `$mul`, `$min`, `$max`,
> `$currentDate`, `$addToSet`, `$push`, and `$pull`.

#### Returns

`UpdateManyResult`

Promise resolving to the update result.

> [accordion] Properties
>
> **success** `boolean` *required*
>
> Whether the operation was successful.
>
> **updated** `number` *required*
>
> Number of entities that were updated.
>
> **has\_more** `boolean` *required*
>
> Whether there are more entities matching the query that were not updated in this batch. When `true`, call `updateMany` again with the same query to update the next batch.

#### Examples

```typescript Basic usage theme={null}
// Archive all completed orders
const result = await base44.entities.Order.updateMany(
  { status: 'completed' },
  { $set: { status: 'archived' } }
);
console.log(`Updated ${result.updated} records`);
```

```typescript Multiple query operators theme={null}
// Flag urgent items that haven't been handled yet
const result = await base44.entities.Task.updateMany(
  { priority: { $in: ['high', 'critical'] }, status: { $ne: 'done' } },
  { $set: { flagged: true } }
);
```

```typescript Multiple update operators theme={null}
// Close out sales records and bump the view count
const result = await base44.entities.Deal.updateMany(
  { category: 'sales' },
  { $set: { status: 'done' }, $inc: { view_count: 1 } }
);
```

```typescript Batched updates theme={null}
// Process all pending items in batches of 500.
// The query filters by 'pending', so updated records (now 'processed')
// are automatically excluded from the next batch.
let hasMore = true;
let totalUpdated = 0;
while (hasMore) {
  const result = await base44.entities.Job.updateMany(
    { status: 'pending' },
    { $set: { status: 'processed' } }
  );
  totalUpdated += result.updated;
  hasMore = result.has_more;
}
```

```typescript Claim a record theme={null}
// Only one user can claim the task, even if several try at the same time
const result = await base44.entities.Task.updateMany(
  { id: taskId, status: 'open' },
  { $set: { status: 'claimed', claimed_by: user.email } }
);
if (result.updated === 1) {
  // This user claimed the task
} else {
  // Someone else claimed it first, or it was no longer open
}
```

```typescript Save only if the record hasn't changed theme={null}
// `version` is a number field defined in the Document schema.
// The edit is saved only if the record is still at the version this user loaded.
const result = await base44.entities.Document.updateMany(
  { id: doc.id, version: doc.version },
  { $set: { body: newBody }, $inc: { version: 1 } }
);
if (result.updated === 0) {
  // Someone else saved a change first. Reload the record and try again.
}
```

***

### bulkUpdate()

> **bulkUpdate**(`data`): `Promise`\<`T`\[]>

Updates the specified records in a single request, each with its own data.

Use this when you already know which records to update and each one needs
different field values. For example, you could update the status and amount
on three separate invoices in one call.

You can update up to 500 records per request.

This isn't a transaction. Each record is written on its own, so if the call
fails partway, the records already written stay written. Learn more about
[concurrent updates](https://docs.base44.com/developers/backend/resources/entities/entity-schemas.md#concurrent-updates).

To apply the same update to all records matching a query, use
[`updateMany()`](#updatemany). To update a single record by ID, use
[`update()`](#update).

#### Parameters

**data** `(Partial\<T\> & \{ id: string \})[]` *required*

Array of objects to update. Each object must contain an `id` field identifying which record to update and any fields to change.

#### Returns

`Promise<T[]>`

Promise resolving to an array of the updated records.

#### Examples

```typescript Basic usage theme={null}
// Update three invoices with different statuses and amounts
const updated = await base44.entities.Invoice.bulkUpdate([
  { id: 'inv-1', status: 'paid', amount: 999 },
  { id: 'inv-2', status: 'cancelled' },
  { id: 'inv-3', amount: 450 }
]);
```

```typescript More than 500 items theme={null}
// Reassign each task to a different owner in batches
const allUpdates = reassignments.map(r => ({ id: r.taskId, owner: r.newOwner }));
for (let i = 0; i < allUpdates.length; i += 500) {
  const batch = allUpdates.slice(i, i + 500);
  await base44.entities.Task.bulkUpdate(batch);
}
```

***

### delete()

> **delete**(`id`): `Promise`\<`DeleteResult`>

Deletes a single record by ID.

The record moves to the entity's trash. To restore it or delete it permanently,
use **Recently deleted** in the [Data tab](https://docs.base44.com/Building-your-app/Managing-your-app-data.md)
or the [Restore entity record](https://docs.base44.com/api-reference/restore-entity-record.md) and
[Permanently delete entity record](https://docs.base44.com/api-reference/permanently-delete-entity-record.md)
endpoints.

#### Parameters

**id** `string` *required*

The unique identifier of the record to delete.

#### Returns

`DeleteResult`

Promise resolving to the deletion result.

> [accordion] Properties
>
> **success** `boolean` *required*
>
> Whether the deletion was successful.

#### Example

```typescript Delete a record theme={null}
const result = await base44.entities.MyEntity.delete('entity-123');
console.log('Deleted:', result.success);
```

***

### deleteMany()

> **deleteMany**(`query`): `Promise`\<`DeleteManyResult`>

Deletes multiple records matching a query.

The matching records move to the entity's trash. To restore them or delete them
permanently, use **Recently deleted** in the
[Data tab](https://docs.base44.com/Building-your-app/Managing-your-app-data.md) or the
[Restore entity records](https://docs.base44.com/api-reference/restore-entity-records.md) and
[Permanently delete entity record](https://docs.base44.com/api-reference/permanently-delete-entity-record.md)
endpoints.

This isn't a transaction. Each record is deleted on its own, so if the call
fails partway, the records already deleted stay deleted. Learn more about
[concurrent updates](https://docs.base44.com/developers/backend/resources/entities/entity-schemas.md#concurrent-updates).

#### Parameters

**query** `Partial\<T\>` *required*

Query matching [`EntityFilterQuery`](#entityfilterquery). Every matching record is deleted.

#### Returns

`DeleteManyResult`

Promise resolving to the deletion result.

> [accordion] Properties
>
> **success** `boolean` *required*
>
> Whether the deletion was successful.
>
> **deleted** `number` *required*
>
> Number of entities that were deleted.

#### Example

```typescript Delete by multiple criteria theme={null}
const result = await base44.entities.MyEntity.deleteMany({
  status: 'completed',
  priority: 'low'
});
console.log('Deleted:', result.deleted);
```

***

### subscribe()

> **subscribe**(`callback`): () => `void`

Subscribes to realtime updates for all records of this entity type.

Establishes a WebSocket connection to receive instant updates when any
record is created, updated, or deleted. Returns an unsubscribe function
to clean up the connection.

#### Parameters

**callback** `RealtimeCallback\<T\>` *required*

Callback function called when an entity changes. The callback receives an event object with the following properties:

* `type`: The type of change that occurred - `'create'`, `'update'`, or `'delete'`.
* `data`: The entity data after the change.
* `id`: The unique identifier of the affected entity.
* `timestamp`: ISO 8601 timestamp of when the event occurred.

#### Returns

Unsubscribe function to stop receiving updates.

#### Example

```typescript Subscribe to all Task changes theme={null}
const unsubscribe = base44.entities.Task.subscribe((event) => {
  console.log(`Task ${event.id} was ${event.type}d:`, event.data);
});

// Later, clean up the subscription
unsubscribe();
```

## Type Definitions

### EntityRecord

> **EntityRecord** = `{ [K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields }`

Combines the [`EntityTypeRegistry`](#entitytyperegistry) schemas with server fields like `id`, `created_date`, and `updated_date` to give the complete record type for each entity. Use this when you need to type variables holding entity data.

#### Example

```typescript Using EntityRecord to get the complete type for an entity theme={null}
// Combine your schema with server fields (id, created_date, etc.)
type TaskRecord = EntityRecord['Task'];

const task: TaskRecord = await base44.entities.Task.create({
  title: 'My task',
  status: 'pending'
});

// Task now includes both your fields and server fields:
console.log(task.id);           // Server field
console.log(task.created_date); // Server field
console.log(task.title);        // Your field
```

### EntityTypeRegistry

Registry mapping entity names to their TypeScript types. The [`types generate`](https://docs.base44.com/developers/references/cli/commands/types-generate) command fills this registry, then [`EntityRecord`](#entityrecord) adds server fields.

### SortField

> **SortField**\<`T`> = `keyof T` | `` `+${keyof T}` `` | `` `-${keyof T}` ``

Sort field type for entity queries.

Accepts any field name from the entity type with an optional prefix:

* `'+'` prefix or no prefix: ascending sort
* `'-'` prefix: descending sort

#### Example

```typescript Specify sort direction by prefixing field names with + or - theme={null}
// Ascending sort
'created_date'
'+created_date'

// Descending sort
'-created_date'
```

### EntityFilterQuery

> **EntityFilterQuery**\<`T`> = `{ [K in keyof T]?: EntityFilterValue<T[K]> }` & `object`

Query object accepted by [`filter()`](#filter),
[`count()`](#count), [`deleteMany()`](#deletemany),
[`updateMany()`](#updatemany), and the `query` field of
`EntityAggregateSpec`.

Field keys are typed from the entity schema. Each field can use an exact value, `null`,
an array shorthand for matching any of the listed values, or a field-level operator
object. Root-level `$and`, `$or`, and `$nor` combine nested filter queries.

Operator values are typed from the field they filter where possible. For example,
numeric fields accept numeric comparison values, string fields accept `$regex`, and
array fields accept `$all` and `$size`.

#### Type Declarations

#### \$and?

> `optional` **\$and**: `EntityFilterQuery`\<`T`>\[]

#### \$or?

> `optional` **\$or**: `EntityFilterQuery`\<`T`>\[]

#### \$nor?

> `optional` **\$nor**: `EntityFilterQuery`\<`T`>\[]

#### Example

```typescript Exact match, a comparison operator, and a nested $or theme={null}
const query: EntityFilterQuery<Task> = {
  status: 'open',
  priority: { $gte: 3 },
  $or: [{ assignee: 'me' }, { team: 'core' }]
};
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.