> ## 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-Modul

> CRUD-Operationen auf Datenmodellen. Zugriff über base44.entities.EntityName.method().

<Warning>
  Diese Seite ist Teil eines KI-Coding-Agent-Skills und für Agenten geschrieben, nicht für Menschen. Für die menschenlesbare Base44-Dokumentation siehe die [Entwicklerdokumentation](/developers).
</Warning>

# Entities-Modul

CRUD-Operationen auf Datenmodellen. Zugriff über `base44.entities.EntityName.method()`.

## Inhalt

* [Methoden](#methoden)
* [Beispiele](#beispiele) (Create, Bulk Create, List, Filter, Get, Update, Delete, Subscribe)
* [User-Entität](#user-entität)
* [Service-Rollen-Zugriff](#service-rollen-zugriff)
* [Berechtigungen](#berechtigungen-rls--fls)

## Methoden

**Hinweis:** Das Maximum für `list()` und `filter()` ist 5.000 Elemente pro Anfrage.

| Methode                                        | Signatur                    | Beschreibung                                                          |
| ---------------------------------------------- | --------------------------- | --------------------------------------------------------------------- |
| `create(data)`                                 | `Promise<T>`                | Einen Datensatz erstellen                                             |
| `bulkCreate(dataArray)`                        | `Promise<T[]>`              | Mehrere Datensätze erstellen                                          |
| `list(sort?, limit?, skip?, fields?)`          | `Promise<Pick<T, K>[]>`     | Alle Datensätze holen (paginiert)                                     |
| `filter(query, sort?, limit?, skip?, fields?)` | `Promise<Pick<T, K>[]>`     | Datensätze holen, die Bedingungen erfüllen                            |
| `get(id)`                                      | `Promise<T>`                | Einzelnen Datensatz per ID holen                                      |
| `update(id, data)`                             | `Promise<T>`                | Datensatz aktualisieren (Teil-Update)                                 |
| `updateMany(query, data)`                      | `Promise<UpdateManyResult>` | Alle passenden Datensätze mit MongoDB-Update-Operatoren aktualisieren |
| `bulkUpdate(dataArray)`                        | `Promise<T[]>`              | Mehrere Datensätze per ID mit je eigenen Daten aktualisieren          |
| `delete(id)`                                   | `Promise<DeleteResult>`     | Datensatz per ID löschen                                              |
| `deleteMany(query)`                            | `Promise<DeleteManyResult>` | Alle passenden Datensätze löschen                                     |
| `importEntities(file)`                         | `Promise<ImportResult<T>>`  | Aus CSV importieren (nur Frontend)                                    |
| `subscribe(callback)`                          | `() => void`                | Für Echtzeit-Updates abonnieren (gibt unsubscribe-Funktion zurück)    |

## Beispiele

### Create

```javascript theme={null}
const task = await base44.entities.Task.create({
  title: "Complete documentation",
  status: "pending",
  dueDate: "2024-12-31"
});
```

### Bulk Create

```javascript theme={null}
const tasks = await base44.entities.Task.bulkCreate([
  { title: "Task 1", status: "pending" },
  { title: "Task 2", status: "pending" }
]);
```

### List mit Pagination

```javascript theme={null}
// Get first 10 records, sorted by created_date descending (max 5,000 per request)
const tasks = await base44.entities.Task.list(
  "-created_date",  // sort (SortField: prefix with - for descending)
  10,               // limit
  0                 // skip
);

// Get next page
const page2 = await base44.entities.Task.list("-created_date", 10, 10);
```

### Filter

```javascript theme={null}
// Simple filter
const pending = await base44.entities.Task.filter({ status: "pending" });

// Multiple conditions
const myPending = await base44.entities.Task.filter({
  status: "pending",
  assignedTo: userId
});

// With sort, limit, skip (max 5,000 per request)
const recent = await base44.entities.Task.filter(
  { status: "pending" },
  "-created_date",  // sort (SortField: prefix with - for descending)
  5,
  0
);

// Select specific fields
const titles = await base44.entities.Task.filter(
  { status: "pending" },
  null,
  null,
  null,
  ["id", "title"]
);
```

### Get per ID

```javascript theme={null}
const task = await base44.entities.Task.get("task-id-123");
```

### Update

```javascript theme={null}
// Partial update - only specified fields change
await base44.entities.Task.update("task-id-123", {
  status: "completed",
  completedAt: new Date().toISOString()
});
```

### Delete

```javascript theme={null}
// Single record
const result = await base44.entities.Task.delete("task-id-123");
console.log("Deleted:", result.success);

// Multiple records matching query
const manyResult = await base44.entities.Task.deleteMany({ status: "archived" });
console.log("Deleted:", manyResult.deleted);
```

### Update Many (MongoDB-Stil)

```javascript theme={null}
// Update all pending tasks to status "in-progress"
const result = await base44.entities.Task.updateMany(
  { status: "pending" },                     // query: which records to update
  { $set: { status: "in-progress" } }        // MongoDB update operator
);
console.log("Updated:", result.updated);

// Increment a counter field
await base44.entities.Task.updateMany(
  { category: "bugs" },
  { $inc: { priority: 1 } }
);
```

### Bulk Update (per ID)

```javascript theme={null}
// Update multiple records, each with different data
const updated = await base44.entities.Task.bulkUpdate([
  { id: "task-1", status: "done", completedAt: new Date().toISOString() },
  { id: "task-2", status: "in-progress", assignedTo: userId },
  { id: "task-3", priority: 5 }
]);
```

### Aus Datei importieren

```javascript theme={null}
// Frontend only: import from CSV/file
const result = await base44.entities.Task.importEntities(file);
if (result.status === "success" && result.output) {
  console.log(`Imported ${result.output.length} records`);
} else {
  console.error(result.details);
}
```

### Echtzeit-Updates abonnieren

```javascript theme={null}
// Subscribe to all changes on Task entity
const unsubscribe = base44.entities.Task.subscribe((event) => {
  console.log(`Task ${event.id} was ${event.type}:`, event.data);
  // event.type is "create", "update", or "delete"
});

// Later: unsubscribe to stop receiving updates
unsubscribe();
```

**Event-Struktur:**

```javascript theme={null}
{
  type: "create" | "update" | "delete",
  data: { ... },       // the entity data
  id: "entity-id",     // the affected entity's ID
  timestamp: "2024-01-15T10:30:00Z"
}
```

## User-Entität

Jede App hat eine eingebaute `User`-Entität mit besonderen Regeln:

* Normale Nutzer können nur **ihren eigenen** Datensatz lesen/aktualisieren
* Nutzer können nicht per `entities.create()` erstellt werden — nutze stattdessen `auth.register()`
* Service-Rolle hat vollen Zugriff auf alle Nutzer-Datensätze

```javascript theme={null}
// Get current user's record
const me = await base44.entities.User.get(currentUserId);

// Service role: get any user
const anyUser = await base44.asServiceRole.entities.User.get(userId);
```

## Service-Rollen-Zugriff

Für Admin-Operationen (Nutzerberechtigungen umgehen):

```javascript theme={null}
// Backend only
const allTasks = await base44.asServiceRole.entities.Task.list();
const allUsers = await base44.asServiceRole.entities.User.list();
```

## Berechtigungen (RLS & FLS)

Der Datenzugriff wird durch **Row Level Security (RLS)** und **Field Level Security (FLS)** gesteuert, die in Entitäts-Schemas definiert sind.

1. **Authentifizierungsebene**: anonym, authentifiziert oder Service-Rolle
2. **RLS-Regeln**: Steuern, welche Datensätze (Zeilen) Nutzer erstellen/lesen/aktualisieren/löschen können
3. **FLS-Regeln**: Steuern, welche Felder Nutzer in zugänglichen Datensätzen lesen/schreiben können

Operationen sind erfolgreich oder scheitern basierend auf diesen Regeln — keine Teil-Ergebnisse.

RLS und FLS werden in Entitäts-Schemadateien (`base44/entities/*.jsonc`) konfiguriert. Siehe [entities-create.md](https://docs.base44.com/developers/skills/base44-sdk/references/../../base44-cli/references/entities-create.md#row-level-security-rls) für Konfigurationsdetails.

**Hinweis:** `asServiceRole` setzt die Rolle des Nutzers auf `"admin"`, umgeht aber RLS NICHT. Deine RLS-Regeln müssen Admin-Zugriff einschließen (z. B. `{ "user_condition": { "role": "admin" } }`), damit Service-Rollen-Operationen erfolgreich sind.

## Type Definitions

### RealtimeEvent

```typescript theme={null}
/** Event types for realtime entity updates. */
type RealtimeEventType = "create" | "update" | "delete";

/** Payload received when a realtime event occurs. */
interface RealtimeEvent<T = any> {
  /** The type of change that occurred. */
  type: RealtimeEventType;
  /** The entity data. */
  data: T;
  /** The unique identifier of the affected entity. */
  id: string;
  /** ISO 8601 timestamp of when the event occurred. */
  timestamp: string;
}

/** Callback function invoked when a realtime event occurs. */
type RealtimeCallback<T = any> = (event: RealtimeEvent<T>) => void;
```

### Result-Typen

```typescript theme={null}
/** Result returned when updating multiple entities. */
interface UpdateManyResult {
  /** Whether the update was successful. */
  success: boolean;
  /** Number of entities that were updated. */
  updated: number;
}

/** Result returned when deleting a single entity. */
interface DeleteResult {
  /** Whether the deletion was successful. */
  success: boolean;
}

/** Result returned when deleting multiple entities. */
interface DeleteManyResult {
  /** Whether the deletion was successful. */
  success: boolean;
  /** Number of entities that were deleted. */
  deleted: number;
}

/** Result returned when importing entities from a file. */
interface ImportResult<T = any> {
  /** Status of the import operation. */
  status: "success" | "error";
  /** Details message, e.g., "Successfully imported 3 entities with RLS enforcement". */
  details: string | null;
  /** Array of created entity objects when successful, or null on error. */
  output: T[] | null;
}
```

### SortField und Server-Felder

```typescript theme={null}
/**
 * Sort field type for entity queries.
 * Supports ascending (no prefix or '+') and descending ('-') sorting.
 * Example: 'created_date', '+created_date', '-created_date'
 */
type SortField<T> = (keyof T & string) | `+${keyof T & string}` | `-${keyof T & string}`;

/** Fields added by the server to every entity record. */
interface ServerEntityFields {
  id: string;
  created_date: string;
  updated_date: string;
  created_by?: string | null;
  created_by_id?: string | null;
  is_sample?: boolean;
}
```

### Type Registry (für typisierte Entitäten)

**So bekommst du typisierte Entitäten:** Die Base44-CLI kann Entitäts-Interfaces und eine Erweiterung von `EntityTypeRegistry` aus deinem Projekt generieren. Wie du sie ausführst, siehe den **base44-cli**-Skill.

```typescript theme={null}
/**
 * Registry mapping entity names to their TypeScript types.
 * Augment this interface with your entity schema (user-defined fields only).
 * Typically populated by the Base44 CLI type generator.
 */
interface EntityTypeRegistry {}

/**
 * Full record type for each entity: schema fields + server-injected fields.
 */
type EntityRecord = {
  [K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields;
};
```

### EntityHandler

```typescript theme={null}
/** Entity handler providing CRUD operations for a specific entity type. */
interface EntityHandler<T = any> {
  /** Lists records with optional pagination and sorting. Max 5,000 per request. */
  list<K extends keyof T = keyof T>(
    sort?: SortField<T>,
    limit?: number,
    skip?: number,
    fields?: K[]
  ): Promise<Pick<T, K>[]>;

  /** Filters records based on a query. Max 5,000 per request. */
  filter<K extends keyof T = keyof T>(
    query: Partial<T>,
    sort?: SortField<T>,
    limit?: number,
    skip?: number,
    fields?: K[]
  ): Promise<Pick<T, K>[]>;

  /** Gets a single record by ID. */
  get(id: string): Promise<T>;

  /** Creates a new record. */
  create(data: Partial<T>): Promise<T>;

  /** Updates an existing record. */
  update(id: string, data: Partial<T>): Promise<T>;

  /** Deletes a single record by ID. */
  delete(id: string): Promise<DeleteResult>;

  /** Deletes multiple records matching a query. */
  deleteMany(query: Partial<T>): Promise<DeleteManyResult>;

  /** Creates multiple records in a single request. */
  bulkCreate(data: Partial<T>[]): Promise<T[]>;

  /**
   * Updates multiple records matching a query using MongoDB update operators.
   * @param query - Filter to select which records to update.
   * @param data - MongoDB update operator object (e.g., `{ $set: { field: value } }`).
   */
  updateMany(query: Partial<T>, data: Record<string, Record<string, any>>): Promise<UpdateManyResult>;

  /** Updates multiple records by ID, each with its own update data. */
  bulkUpdate(data: (Partial<T> & { id: string })[]): Promise<T[]>;

  /** Imports records from a file (frontend only). */
  importEntities(file: File): Promise<ImportResult<T>>;

  /** Subscribes to realtime updates. Returns unsubscribe function. */
  subscribe(callback: RealtimeCallback<T>): () => void;
}
```

### EntitiesModule

```typescript theme={null}
/** Entities module: typed registry keys get typed handlers; dynamic access remains untyped. */
type EntitiesModule = TypedEntitiesModule & DynamicEntitiesModule;

type TypedEntitiesModule = {
  [K in keyof EntityTypeRegistry]: EntityHandler<EntityRecord[K]>;
};

type DynamicEntitiesModule = {
  [entityName: string]: EntityHandler<any>;
};
```

<Note>Diese Seite wurde mit KI übersetzt. Für die genauesten und aktuellsten Informationen siehe die [englische Version](/). </Note>
