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

# Database

> Read, insert, update, and delete documents in any collection using the SDK database module.

Access database methods via `client.db`. Collections must be created in the [urBackend Dashboard](https://urbackend.bitbros.in) before you can interact with them.

Methods that return documents accept a generic type parameter `T` (extending `DocumentData`) so returned documents are fully typed. Methods like `delete()` return status objects and do not accept `T`.

## Row-Level Security (RLS)

If a collection has RLS enabled, token requirements depend on mode:

* `public-read`: token is required for writes (`insert`, `update`, `patch`, `delete`), optional for reads.
* `private`: token is required for both reads and writes when using a publishable key (`pk_live_...`).

Example pattern:

```typescript theme={null}
const { accessToken } = await client.auth.login({ ... });
await client.db.insert('posts', { content: 'Hello' }, accessToken);
```

***

## getAll

Fetch documents from a collection with optional filtering, sorting, and pagination.

```typescript theme={null}
getAll<T extends DocumentData>(collection: string, params?: QueryParams, token?: string): Promise<T[]>
```

**Query Parameters (`params`)**

| Parameter  | Type                 | Description                                       |
| ---------- | -------------------- | ------------------------------------------------- |
| `filter`   | `object`             | Filter by field suffixes (e.g. `{ age_gt: 18 }`). |
| `sort`     | `string`             | Sort order (e.g. `"createdAt:desc"`).             |
| `limit`    | `number`             | Max documents to return (max 100).                |
| `page`     | `number`             | Page number for pagination.                       |
| `populate` | `string \| string[]` | Expand Reference fields into full objects.        |

**Example**

```typescript theme={null}
const products = await client.db.getAll<Product>('products', {
  filter: { category: 'electronics', price_lt: 500 },
  sort: 'price:asc',
  limit: 20
});

// For private-mode reads with pk_live_..., pass the user token:
const privateItems = await client.db.getAll<Product>('products', { limit: 10 }, accessToken);
```

***

## getOne

Fetch a single document by its ID.

```typescript theme={null}
getOne<T extends DocumentData>(collection: string, id: string, options?: { populate?: string | string[] }, token?: string): Promise<T>
```

**Example**

```typescript theme={null}
const product = await client.db.getOne<Product>('products', 'id_123', { populate: 'vendor' });
```

***

## count

Count documents in a collection.

```typescript theme={null}
count(collection: string, params?: QueryParams, token?: string): Promise<number>
```

Use `token` for private-mode reads when using publishable keys.

***

## insert

Insert a new document. If RLS is enabled, the `token` parameter is required.

```typescript theme={null}
insert<T extends DocumentData>(collection: string, data: Record<string, unknown>, token?: string): Promise<T>
```

***

## update

Update an existing document by its ID. This performs a **full replacement** of the document fields.

```typescript theme={null}
update<T extends DocumentData>(collection: string, id: string, data: Record<string, unknown>, token?: string): Promise<T>
```

***

## patch

Partially update a document. Only the fields provided in `data` will be modified.

```typescript theme={null}
patch<T extends DocumentData>(collection: string, id: string, data: Record<string, unknown>, token?: string): Promise<T>
```

**Example**

```typescript theme={null}
// Only updates the price, leaves other fields unchanged
await client.db.patch('products', 'id_123', { price: 45 });
```

***

## delete

Delete a document by its ID.

```typescript theme={null}
delete(collection: string, id: string, token?: string): Promise<{ deleted: boolean }>
```

***

## TypeScript Support

Define your interfaces to get full IDE autocomplete:

```typescript theme={null}
interface BlogPost {
  _id: string;
  title: string;
  author: string;
}

const posts = await client.db.getAll<BlogPost>('posts');
posts[0].title; // typed as string
```
