# CreatePromise

CreatePromise provides chainable methods for configuring CREATE operations.

The `CreatePromise` class provides a chainable interface for configuring CREATE operations before execution. It extends `Promise`, allowing you to `await` it directly or chain configuration methods.

**Returned by:** [`SurrealQueryable.create()`](/docs/reference/javascript/api/core/surreal-queryable.md#create)

**Source:** [query/create.ts](https://github.com/surrealdb/surrealdb.js/blob/main/packages/sdk/src/query/create.ts)

## Type parameters

- `T` - The result type
- `I` - The input type for record data
- `J` - Boolean indicating if result is JSON (default: `false`)

## Configuration methods

### `.content()` {#content}

Set the complete content for the new record.

```ts title="Method Syntax"
createPromise.content(data)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>data</code> <label label="required" /></td>
            <td><code>Values&lt;I&gt;</code></td>
            <td>The record data (excluding id field).</td>
        </tr>
    </tbody>
</table>

#### Returns
`CreatePromise<T, I, J>` - Chainable promise

#### Examples

```ts title="Create with Specific ID"
const user = await db.create(new RecordId('users', 'john'))
    .content({
        name: 'John Doe',
        email: 'john@example.com',
        age: 30
    });
```

```ts title="Create with Auto-Generated ID"
const user = await db.create(new Table('users'))
    .content({
        name: 'Jane Doe',
        email: 'jane@example.com',
        age: 28
    });
```

---

### `.patch()` {#patch}

Apply JSON Patch operations to set record data.

```ts title="Method Syntax"
createPromise.patch(operations)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>operations</code> <label label="required" /></td>
            <td><code>Values&lt;I&gt;</code></td>
            <td>JSON Patch operations to apply.</td>
        </tr>
    </tbody>
</table>

#### Returns
`CreatePromise<T, I, J>` - Chainable promise

#### Example

```ts
const user = await db.create(new Table('users'))
    .patch([
        { op: 'add', path: '/name', value: 'John' },
        { op: 'add', path: '/email', value: 'john@example.com' }
    ]);
```

---

### `.output()` {#output}

Specify which fields to return in the response.

```ts title="Method Syntax"
createPromise.output(fields)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>fields</code> <label label="required" /></td>
            <td><code>Output</code></td>
            <td>Output specification: <code>"NONE"</code>, <code>"BEFORE"</code>, <code>"AFTER"</code>, <code>"DIFF"</code>, or field list.</td>
        </tr>
    </tbody>
</table>

#### Returns
`CreatePromise<T, I, J>` - Chainable promise

#### Examples

```ts title="Return Specific Fields"
const user = await db.create(new Table('users'))
    .content(userData)
    .output('id', 'name');
// Returns only id and name
```

```ts title="Return Full Record"
const user = await db.create(new Table('users'))
    .content(userData)
    .output('AFTER');
// Returns complete created record
```

```ts title="Return Nothing"
await db.create(new Table('logs'))
    .content(logData)
    .output('NONE');
// Returns undefined, useful for fire-and-forget
```

---

### `.timeout()` {#timeout}

Set a timeout for the operation.

```ts title="Method Syntax"
createPromise.timeout(duration)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>duration</code> <label label="required" /></td>
            <td><code><a href="/docs/reference/javascript/api/values/duration.md">Duration</a></code></td>
            <td>Maximum time to wait for operation completion.</td>
        </tr>
    </tbody>
</table>

#### Returns
`CreatePromise<T, I, J>` - Chainable promise

#### Example

```ts
const user = await db.create(new Table('users'))
    .content(userData)
    .timeout(Duration.parse('5s'));
```

---

### `.version()` {#version}

Create the record at a specific version (for versioned storage engines).

```ts title="Method Syntax"
createPromise.version(timestamp)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>timestamp</code> <label label="required" /></td>
            <td><code><a href="/docs/reference/javascript/api/values/datetime.md">DateTime</a></code></td>
            <td>The version timestamp.</td>
        </tr>
    </tbody>
</table>

#### Returns
`CreatePromise<T, I, J>` - Chainable promise

#### Example

```ts
const user = await db.create(new Table('users'))
    .content(userData)
    .version(DateTime.now());
```

---

### `.retry()` {#retry}

Retry the operation with exponential backoff if it fails due to a write conflict. Off by default; passing an options object (or calling with no arguments) opts the operation in.

This overrides the connection-wide default set via the [`retry`](/docs/reference/javascript/api/types/#connectoptions) option on `ConnectOptions`.

```ts title="Method Syntax"
createPromise.retry(options?)
```

#### Parameters
<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>options</code> <label label="optional" /></td>
            <td><code>Partial&lt;<a href="/docs/reference/javascript/api/types/#retryoptions">RetryOptions</a>&gt;</code></td>
            <td>Retry configuration. If omitted, retry is enabled with the default configuration.</td>
        </tr>
    </tbody>
</table>

#### Returns
`CreatePromise<T, I, J>` - Chainable promise

#### Example

```ts
const user = await db.create(new Table('users'))
    .content(userData)
    .retry({ attempts: 3 });
```

---

### `.json()` {#json}

Return result as JSON string instead of parsed object.

```ts title="Method Syntax"
createPromise.json()
```

#### Returns
`CreatePromise<T, I, true>` - Promise returning JSON string

#### Example

```ts
const jsonString = await db.create(new Table('users'))
    .content(userData)
    .json();
```

---

### `.compile()` {#compile}

Compile the query into a `BoundQuery` without executing it.

```ts title="Method Syntax"
createPromise.compile()
```

#### Returns
`BoundQuery<[T]>` - The compiled query

#### Example

```ts
const query = db.create(new Table('users'))
    .content(userData)
    .compile();
```

---

### `.stream()` {#stream}

Stream the operation result (useful when creating multiple records).

```ts title="Method Syntax"
createPromise.stream()
```

#### Returns
`AsyncIterableIterator` - Async iterator

#### Example

```ts
const results = db.create(new Table('users'))
    .content(multipleUsers);
    
for await (const user of results.stream()) {
    console.log('Created:', user);
}
```

## Complete examples

### Basic creation

```ts
import { Surreal, RecordId, Table } from 'surrealdb';

const db = new Surreal();
await db.connect('ws://localhost:8000');

// Create with specific ID
const user = await db.create(new RecordId('users', 'john'))
    .content({
        name: 'John Doe',
        email: 'john@example.com',
        role: 'admin'
    });

// Create with auto-generated ID
const post = await db.create(new Table('posts'))
    .content({
        title: 'Hello World',
        content: 'My first post',
        author: new RecordId('users', 'john')
    });
```

### Creation with output control

```ts
// Only return the ID
const { id } = await db.create(new Table('users'))
    .content(userData)
    .output('id');

// Return specific fields
const summary = await db.create(new Table('users'))
    .content(userData)
    .output('id', 'name', 'created_at');
```

### Bulk creation with streaming

```ts
const users = [
    { name: 'Alice', email: 'alice@example.com' },
    { name: 'Bob', email: 'bob@example.com' },
    { name: 'Carol', email: 'carol@example.com' }
];

for await (const user of db.create(new Table('users')).content(users).stream()) {
    console.log(`Created user: ${user.name} with ID: ${user.id}`);
}
```

### With relationships

```ts
const post = await db.create(new Table('posts'))
    .content({
        title: 'New Post',
        content: 'Post content here',
        author: new RecordId('users', 'john'),
        tags: [
            new RecordId('tags', 'javascript'),
            new RecordId('tags', 'tutorial')
        ],
        created_at: DateTime.now()
    });
```

### Error handling

```ts
try {
    const user = await db.create(new RecordId('users', 'existing'))
        .content(userData);
} catch (error) {
    if (error instanceof ResponseError) {
        console.error('User already exists:', error.message);
    }
}
```

### With timeout

```ts
const user = await db.create(new Table('users'))
    .content(complexUserData)
    .timeout(Duration.parse('10s'));
```

## Chaining pattern

All configuration methods return a new `CreatePromise`, allowing method chaining:

```ts
const result = await db.create(new Table('users'))
    .content(userData)
    .output('id', 'name', 'email')
    .timeout(Duration.parse('5s'));
```

## See also

- [SurrealQueryable.create()](/docs/reference/javascript/api/core/surreal-queryable.md#create) - Method that returns CreatePromise
- [InsertPromise](/docs/reference/javascript/api/queries/insert-promise.md) - Bulk insertion
- [UpsertPromise](/docs/reference/javascript/api/queries/upsert-promise.md) - Insert or replace
- [Query overview](/docs/reference/javascript/api/queries/) - All query builder classes
