[data-reveal]{opacity:1!important;transform:none!important}
Database

Datum

The Datum<T> class represents a single value in the query system. It extends Query<T> and provides methods for accessing fields, applying transformations, and performing foreign key lookups on individual values.

Class Definition

class Datum<T> extends Query<T> {
  cast<U>(): Datum<U>;
  key<K extends keyof NonNullable<T>>(key: K, def?: unknown): Datum<NonNullable<T>[K]>;
  default<U>(val: Value<U>): Datum<Exclude<T, undefined | null> | U>;
  do<U>(mapper: (val: ValueProxy<T>) => U): Datum<ExtractType<U>>;
  lookup<U>(other: Selection<U>, localKey: keyof T, otherKey: keyof U): Datum<...>;
  pluck(...fields: string[]): Datum<Partial<T>>;
}

Field Access

The key method retrieves a field from a document datum. You can chain key calls for nested field access. An optional default value can be provided for the case when the field is undefined.

import { Schema } from "@antelopejs/interface-database";

const schema = Schema.get("myapp")!;
const users = schema.instance().table("users");

// Access a field
const name = await users.get("user-123").key("name");

// Access a nested field
const city = await users.get("user-123").key("address").key("city");

// Provide a default value
const phone = await users.get("user-123").key("phone", "N/A");

Default Values

The default method provides a fallback value when the datum is null or undefined.

const user = await users.get("maybe-missing").default({
  _id: "guest",
  name: "Guest User",
  role: "visitor",
});

Transform with do()

The do method applies a transformation function to the datum. The callback receives a ValueProxy<T> that provides operators for building expressions.

const formatted = await users.get("user-123").do((user) => ({
  displayName: user.key("name"),
  contact: user.key("email"),
  hasPhone: user.key("phone").ne(undefined),
}));

Foreign Key Lookup

The lookup method replaces a foreign key field with the referenced document from another table.

interface Post {
  _id: string;
  title: string;
  authorId: string;
}

interface User {
  _id: string;
  name: string;
}

const post = await schema
  .instance()
  .table<Post>("posts")
  .get("post-1")
  .lookup(schema.instance().table<User>("users"), "authorId", "_id");

// post.authorId is now the full User object
console.log(post.authorId.name);

Field Selection

The pluck method selects specific fields from a document datum, discarding the rest.

const profile = await users.get("user-123").pluck("name", "email", "avatar");

Type Casting

The cast method changes the TypeScript type of the datum without performing any runtime conversion. Use this when you know the actual type differs from what the compiler infers.

const raw = users.get("user-123").cast<{ name: string; role: string }>();