Realtime > Collection Subscriptions
Realtime > Collection SubscriptionsKroxt BaaS SDK v1.0.5

Collection Subscriptions

Subscribe to document insert, update, or delete mutations happening inside MongoDB.

realtime.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const channel = baas.realtime.collection("todos").subscribe();

channel.on("created", (todo) => {
  console.log("New todo created:", todo);
});

channel.on("updated", (todo) => {
  console.log("Todo updated:", todo);
});

channel.on("deleted", ({ documentId }) => {
  console.log("Todo deleted ID:", documentId);
});

// Clean up connection:
channel.unsubscribe();

TypeScript Type Integration

Subscribe with generic interface arguments to type the mutation payloads:

types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
import type { Document } from "@kroxt/baas-sdk";

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

const channel = baas.realtime.collection("todos").subscribe();

// doc is typed as Document<Todo> automatically
channel.on("created", (doc: Document<Todo>) => {
  console.log("Created Todo text:", doc.data.text);
});