Database > CRUD Operations
Database > CRUD OperationsKroxt BaaS SDK v1.0.5

CRUD Operations

Create Document:
db.ts
1
2
3
4
const newTodo = await baas.collection("todos").create({
  text: "Setup MongoDB schema",
  completed: false,
});
Get Single Document by ID:
db.ts
1
2
const todo = await baas.collection("todos").get("DOCUMENT_ID");
console.log("Todo item data:", todo.data.text);
Fetch All / Matching Documents:
db.ts
1
2
3
4
5
6
7
8
9
// Fetch all documents
const allTodos = await baas.collection("todos").find();

// Fetch matching documents directly (alias to .get())
const list = await baas.collection("todos")
  .where("completed", "equals", false)
  .orderBy("createdAt", "desc")
  .limit(10)
  .find();
Count Documents:
db.ts
1
2
3
4
5
6
7
// Count all documents in the collection
const totalCount = await baas.collection("todos").count();

// Count with query filters applied
const pendingCount = await baas.collection("todos")
  .where("completed", "equals", false)
  .count();
Paginated Search Queries:
db.ts
1
2
3
4
5
6
7
const result = await baas.collection("todos").paginate({
  page: 1,
  limit: 10,
});
console.log("Items on page 1:", result.items);
console.log("Total matched pages:", result.pages);
console.log("Has next page:", result.hasNext);
Update Document by ID:
db.ts
1
2
3
await baas.collection("todos").update("DOCUMENT_ID", {
  completed: true,
});
Delete Document by ID:
db.ts
1
await baas.collection("todos").delete("DOCUMENT_ID");

TypeScript Type Integration

Pass your custom schema interface as a generic to collection<T>(). This enables full input type validation and type autocomplete on the returned Document<T> envelope:

types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import type { Document } from "@kroxt/baas-sdk";

interface Todo {
  text: string;
  completed: boolean;
}

const todosCollection = baas.collection<Todo>("todos");

// Create returns a typed Document<Todo>
const newTodo = await todosCollection.create({
  text: "Setup TypeScript docs",
  completed: false, // Type checked!
});

// Query returns Document<Todo>[]
const list: Document<Todo>[] = await todosCollection
  .where("completed", "equals", false)
  .get();

list.forEach((doc) => {
  console.log("System ID:", doc._id);         // Envelope property
  console.log("Todo Text:", doc.data.text);   // Custom fields are nested inside .data
});