• Start

Languages

/

JavaScript

/

API Reference

/

Query builders

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()

Source: query/create.ts

  • T - The result type

  • I - The input type for record data

  • J - Boolean indicating if result is JSON (default: false)

Set the complete content for the new record.

Method Syntax
createPromise.content(data)

Parameter

Type

Description

dataValues<I>

The record data (excluding id field).

`CreatePromise` - Chainable promise

Create with Specific ID
const user = await db.create(new RecordId('users', 'john'))
    .content({
        name: 'John Doe',
        email: 'john@example.com',
        age: 30
    });
Create with Auto-Generated ID
const user = await db.create(new Table('users'))
    .content({
        name: 'Jane Doe',
        email: 'jane@example.com',
        age: 28
    });

Apply JSON Patch operations to set record data.

Method Syntax
createPromise.patch(operations)

Parameter

Type

Description

operationsValues<I>

JSON Patch operations to apply.

`CreatePromise` - Chainable promise

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

Specify which fields to return in the response.

Method Syntax
createPromise.output(fields)

Parameter

Type

Description

fieldsOutput

Output specification:

"NONE"

,

"BEFORE"

,

"AFTER"

,

"DIFF"

, or field list.

`CreatePromise` - Chainable promise

Return Specific Fields
const user = await db.create(new Table('users'))
    .content(userData)
    .output('id', 'name');
// Returns only id and name
Return Full Record
const user = await db.create(new Table('users'))
    .content(userData)
    .output('AFTER');
// Returns complete created record
Return Nothing
await db.create(new Table('logs'))
    .content(logData)
    .output('NONE');
// Returns undefined, useful for fire-and-forget

Set a timeout for the operation.

Method Syntax
createPromise.timeout(duration)

Parameter

Type

Description

duration

Duration

Maximum time to wait for operation completion.

`CreatePromise` - Chainable promise

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

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

Method Syntax
createPromise.version(timestamp)

Parameter

Type

Description

timestamp

DateTime

The version timestamp.

`CreatePromise` - Chainable promise

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

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 option on ConnectOptions.

Method Syntax
createPromise.retry(options?)

Parameter

Type

Description

options

Partial

RetryOptions

Retry configuration. If omitted, retry is enabled with the default configuration.

`CreatePromise` - Chainable promise

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

Return result as JSON string instead of parsed object.

Method Syntax
createPromise.json()

`CreatePromise` - Promise returning JSON string

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

Compile the query into a BoundQuery without executing it.

Method Syntax
createPromise.compile()

`BoundQuery` - The compiled query

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

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

Method Syntax
createPromise.stream()

AsyncIterableIterator - Async iterator

const results = db.create(new Table('users'))
    .content(multipleUsers);
    
for await (const user of results.stream()) {
    console.log('Created:', user);
}
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')
    });
// 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');
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}`);
}
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()
    });
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);
    }
}
const user = await db.create(new Table('users'))
    .content(complexUserData)
    .timeout(Duration.parse('10s'));

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

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

Was this page helpful?