SurrealDB
SurrealDB Docs Logo

Enter a search query

Navigation

Concepts

Value types

Value types

The JavaScript SDK provides custom classes for SurrealDB-specific data types that don’t have direct JavaScript equivalents. These classes ensure type safety, preserve database precision, validate input, and integrate seamlessly with the SDK’s query methods.

API References

ClassDescription
RecordIdType-safe record identifiers with table and ID components
TableType-safe table references for query methods
DateTimeDatetime values with nanosecond precision
DurationTime duration values with multiple unit support
DecimalArbitrary precision decimal numbers
UuidUniversally unique identifiers (v4 and v7)
RangeBounded or unbounded range values
FileRefReferences to files stored in SurrealDB
Geometry*GeoJSON geometry types (Point, Line, Polygon, etc.)

Type mapping

SurrealQL types map to JavaScript types as follows:

SurrealQL typeJavaScript typeExample
boolbooleantrue, false
int, floatnumber42, 3.14
stringstring”hello”
nullnullnull
noneundefinedundefined
arrayArray[1, 2, 3]
objectObject{ key: "value" }
setSetnew Set([1, 2, 3])
bytesUint8Arraynew Uint8Array([…])
recordRecordIdnew RecordId(‘users’, ‘john’)
Tablenew Table(‘users’)
datetimeDateTimeDateTime.now()
durationDurationDuration.parse(‘1h30m’)
decimalDecimalnew Decimal(‘19.99’)
uuidUuidUuid.v7()
geometryGeometry*new GeometryPoint([1, 2])
rangeRangenew Range(1, 10)
fileFileRefrecord.avatar

RecordId and Table

A RecordId represents a unique record identifier consisting of a table name and an ID value. A Table represents a table reference. In the v2 SDK, query methods no longer accept plain strings as table names — you must use the Table class to avoid ambiguity between table names and record IDs.

import { RecordId, Table } from 'surrealdb'; const userId = new RecordId('users', 'john'); const user = await db.select(userId); const usersTable = new Table('users'); const allUsers = await db.select(usersTable); const parsed = RecordId.parse('users:john');

The ID component of a RecordId can be a string, number, bigint, Uuid, array, or object. The Table class also supports a type parameter for type-safe query results.

const users = new Table<User>('users');
const results: User[] = await db.select(users);

DateTime and Duration

A DateTime represents a point in time with nanosecond precision. Unlike JavaScript’s native Date which is limited to millisecond precision, DateTime preserves the full precision of SurrealDB timestamps. A Duration represents a span of time using SurrealQL duration syntax.

import { DateTime, Duration } from 'surrealdb'; const now = DateTime.now(); const parsed = DateTime.parse('2024-01-15T12:00:00.123456789Z'); const jsDate = now.toDate(); const iso = now.toString(); const duration = Duration.parse('1h30m45s'); const ms = duration.toMilliseconds(); const seconds = duration.toSeconds();

Decimal

A Decimal represents an arbitrary-precision decimal number. This avoids the floating-point precision issues that occur with JavaScript’s number type.

import { Decimal } from 'surrealdb'; const price = new Decimal('19.99'); const display = price.toString(); const number = price.toNumber();
Note

Converting a Decimal to a number with .toNumber() may lose precision. Use .toString() when precision matters.

Uuid

A Uuid represents a universally unique identifier. The class supports generating both v4 (random) and v7 (time-ordered) UUIDs.

import { Uuid } from 'surrealdb'; const random = Uuid.v4(); const timeOrdered = Uuid.v7(); const parsed = Uuid.parse('550e8400-e29b-41d4-a716-446655440000');

Range

A Range represents a bounded or unbounded range of values. Ranges are used in SurrealQL for selecting slices of records by ID or filtering numeric and temporal values. A RecordIdRange is a specialization for querying a range of records from a table.

import { Range, RecordIdRange } from 'surrealdb'; const numericRange = new Range(1, 10); const idRange = new RecordIdRange('users', { begin: 'a', end: 'f' }); const slice = await db.select(idRange);

FileRef

A FileRef represents a reference to a file stored in SurrealDB. File references are returned when working with file uploads and contain metadata about the stored file.

const [record] = await db.query('SELECT avatar FROM user:john'); if (record.avatar instanceof FileRef) { console.log(record.avatar.bucket); console.log(record.avatar.key); }

Geometry types

The SDK provides classes for all GeoJSON geometry types: GeometryPoint, GeometryLine, GeometryPolygon, GeometryMultiPoint, GeometryMultiLine, GeometryMultiPolygon, and GeometryCollection.

import { GeometryPoint, GeometryLine, GeometryPolygon } from 'surrealdb'; const point = new GeometryPoint([longitude, latitude]); const line = new GeometryLine([ new GeometryPoint([1, 2]), new GeometryPoint([3, 4]), ]);

Parsing from strings

Most value classes support parsing from string representations, matching the syntax used in SurrealQL.

const recordId = RecordId.parse('users:john'); const datetime = DateTime.parse('2024-01-15T12:00:00Z'); const duration = Duration.parse('1h30m45s'); const uuid = Uuid.parse('550e8400-e29b-41d4-a716-446655440000');

Parsing validates the input format and throws an error if the string is invalid.

Using native dates

By default, the SDK returns DateTime instances for datetime values. If you prefer native JavaScript Date objects (at the cost of nanosecond precision), you can enable useNativeDates in the codec options.

const db = new Surreal({ codecOptions: { useNativeDates: true, }, });

String prefixes

The SDK provides tagged template functions that replicate SurrealQL’s string prefixes in JavaScript. These create the corresponding value class from a template literal.

import { s, d, r, u } from 'surrealdb'; const string = s`I am a string`; const date = d`2024-05-06T17:44:57.085Z`; const record = r`person:tobie`; const uuid = u`92b84bde-39c8-4b4b-92f7-626096d6c4d9`;

Best practices

Use type parameters for type-safe queries

const users = new Table<User>('users'); const results: User[] = await db.select(users); const userId = new RecordId<'users', string>('users', 'john');

Prefer value classes over raw strings

await db.select(new RecordId('users', 'john')); // Avoid string-based queries when possible await db.query('SELECT * FROM users:john');

Validate parsed input

try { const uuid = Uuid.parse(userInput); } catch (error) { console.error('Invalid UUID format'); }

Learn more