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

SingleSelection

The SingleSelection<T> class represents a reference to a single document in a table. It extends Datum<T> and provides methods for updating, replacing, deleting, and monitoring changes to an individual document.

Class Definition

class SingleSelection<T> extends Datum<T> {
  update(document: DeepPartial<T>): Query<number>;
  update<U>(document: (val: ValueProxy<T>) => U): Query<number>;
  replace(document: DeepPartial<T>): Query<number>;
  delete(): Query<number>;
  changes(): Query<Changes<T>[]>;
}

Create a SingleSelection

SingleSelection objects are produced by calling get() on a table:

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

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

// Get a document by primary key
const user = users.get("user-123");

Read a Document

Since SingleSelection extends Datum, you can execute it directly to retrieve the document value:

const user = await users.get("user-123");

if (user) {
  console.log("Found:", user.name);
}

// Access specific fields
const email = await users.get("user-123").key("email");
console.log("Email:", email);

// Transform with do()
const display = await users.get("user-123").do((u) => ({
  label: u.key("name"),
  contact: u.key("email"),
}));

Update a Document

The update method modifies fields in the document. Unmentioned fields remain unchanged. Returns the number of modified documents.

// Update with a partial object
const count = await users.get("user-123").update({
  status: "active",
  lastLogin: new Date(),
});

// Update with a function for computed values
await users.get("user-123").update((user) => ({
  loginCount: user.key("loginCount").add(1),
  lastLogin: new Date(),
}));

Replace a Document

The replace method substitutes the entire document with new data.

const count = await users.get("user-123").replace({
  _id: "user-123",
  name: "New Name",
  email: "[email protected]",
  role: "user",
});

Delete a Document

The delete method removes the document from the table.

const count = await users.get("user-123").delete();

if (count === 1) {
  console.log("User deleted successfully");
}

Monitor Changes

The changes method returns change events for the document. Each event contains a changeType and the oldValue/newValue of the document.

const changes = await users.get("user-123").changes();

for (const change of changes) {
  console.log("Type:", change.changeType); // "added" | "removed" | "modified"
  console.log("Old:", change.oldValue);
  console.log("New:", change.newValue);
}

Inherited Methods

Since SingleSelection extends Datum, it inherits:

  • key() - Access a field by name
  • default() - Provide a fallback value for null
  • do() - Apply a transformation function
  • lookup() - Perform a foreign key lookup
  • pluck() - Select specific fields
  • cast() - Change the TypeScript type

See Datum for complete details.