Skip to content

Collections

Bazaar provides document-oriented (NoSQL) and schema-less databases. Each database belongs to one owner (a user, team, org, or the app itself) and one app. A database contains collections which are analogous to tables in a relational database. Collections are made up of documents, or docs, analogous to rows in a relational database.

To use a collection, create a collection object. By default, a collection object interacts with the database of the authenticated user.

A collection will be lazily created the first time someone tries to interact with it. Names starting with _ are reserved.

const exampleCollection = bzr.collection("example-collection");
// Use the collection
const allDocs = await exampleCollection.getAll();

When using TypeScript, you can specify the type of the collection doc.

type TaskDoc = {
id: string; // required
name: string;
completed: boolean;
};
const tasksCollection = bzr.collection<TaskDoc>("tasks");

Collection doc types must include an id of type string. That is, it must extend or conform to the Doc type.

type Doc = {
id: string;
};

To use a collection in another user’s, a team’s, an org’s, or the app’s database, create a context for that owner:

const ctx = await bzr.createContext({ ownerId: "collection-owners-id" });
const exampleCollection = ctx.collection("example-collection");

When a collection is lazily created, you might want to take some action. For example, to set permissions or insert some initial data. In an org’s or team’s database, only its admins can create one. You can do this as follows:

const options = {
onCreate: async () => {
await exampleCollection.insertOne({
id: "1",
task: "Create first Bazaar app!",
});
},
};
const exampleCollection = bzr.collection("example-collection", options);

Get all docs from a collection.

const docs = await exampleCollection.getAll(filter, options);

The filter and options parameters are optional:

const allDocs = await exampleCollection.getAll();

A filter allows you to get only a subset of documents. Learn how Filtering works.

Use the options parameter to set offsets and order to further control returned docs.

import { OrderByType } from "@bzr/bazaar";
const filter = {}; // No filter
const options = {
startOffset: 10,
endOffset: 20,
orderBy: { height: OrderByType.DESC },
};
const docs = await exampleCollection.getAll(filter, options);

startOffset is included and endOffset is not, so the example returns documents 10 to 19. Both must be whole numbers ≥ 0.

Offsets are useful, but for a more ergonomic way to work with pagination, there is getPage. Page numbers start at 0.

const pageNumber = 2;
const pageSize = 20;
const paginatedDocs = await exampleCollection.getPage(pageNumber, pageSize);

Like getAll, getPage also takes optional filter and options parameters.

const paginatedDocs = await exampleCollection.getPage(
pageNumber,
pageSize,
filter,
options,
);

The options parameter allows you to order the returned docs.

const options = { orderBy: { height: OrderByType.DESC } };

Get a single doc.

const doc = await exampleCollection.getOne("example-doc-id");

If no document with this ID exists, null is returned.

Insert a new doc with an auto-generated ID.

const docId = await exampleCollection.insertOne({ name: "Skylar" });

Insert a new doc with a specific ID.

const docId = await exampleCollection.insertOne({ id: "1", name: "Skylar" });

The ID must be unique; inserting a document with an existing ID fails with AlreadyExists.

Update a doc.

const message = await exampleCollection.updateOne(docId, partialDoc);

Nested objects are merged. Arrays and other values are replaced. If no doc has this ID, nothing changes.

For example, if you have a doc:

const doc = {
id: "1",
name: "Leo",
age: 40,
weightKg: 80,
};

And update as follows:

const message = await exampleCollection.updateOne("1", { weightKg: 82 });

The result will be:

const doc = {
id: "1",
name: "Leo",
age: 40,
weightKg: 82,
};

Replace an existing doc with a new one. The new doc completely overwrites the existing doc. If no doc has this ID, nothing changes.

const newDoc = { id: "example-doc-id", name: "New Name", completed: false };
const message = await exampleCollection.replaceOne("example-doc-id", newDoc);

Delete all documents that match a filter, or every document in the collection without one. This action cannot be undone.

const message = await exampleCollection.deleteAll(filter);

Delete a specific document from a collection by its ID.

const message = await exampleCollection.deleteOne("example-doc-id");

Receive realtime updates whenever any document in the collection changes. Returns an unsubscribe function.

const unsubscribe = await exampleCollection.subscribeAll(filter, listener);

Like in getAll, the filter can be empty ({}) to watch every document.

A connection holds up to 1000 subscriptions, and a user up to 2000 per app. Past that, subscribing fails with RequestLimit.

The listener is an object that contains optional callbacks to be run when a document is added, updated, or deleted. It has the following type:

type SubscribeListener<T extends Doc> = {
onAdd?: (doc: T) => void;
onChange?: (oldDoc: T, newDoc: T) => void;
onDelete?: (doc: T) => void;
onInitial?: (doc: T) => void;
};

onInitial usage notes:

  • When a listener is first invoked and an onInitial function is provided, it will be called for each existing document in the collection.
  • The onInitial callback serves as a convenient alternative to manually fetching and iterating over all documents in a collection.
  • onInitial is particularly useful for initializing local state with existing data from the collection.

For example, instead of:

const docs = await exampleCollection.getAll();
docs.forEach((doc) => addToLocalState(doc));
await exampleCollection.subscribeAll(
{},
{
onAdd: (doc) => addToLocalState(doc),
},
);

You can use:

await exampleCollection.subscribeAll(
{},
{
onInitial: (doc) => addToLocalState(doc),
onAdd: (doc) => addToLocalState(doc),
// ... other callbacks as needed
},
);

This approach simplifies the process of initially populating local state with existing documents from the collection.

Receive realtime updates for a specific document in the collection.

const docId = "example-doc-id";
const unsubscribe = await exampleCollection.subscribeOne(docId, listener);

Returns an unsubscribe function.

See Subscribe Listener docs.

When subscribing to change events, a common use case is to keep a local array or object in sync with the database. For those cases you can utilize the arrayMirrorSubscribeListener and objectMirrorSubscribeListener subscribe listener helpers to avoid writing boilerplate to update arrays and objects.

const unsubscribe = await exampleCollection.subscribeAll(
{},
arrayMirrorSubscribeListener(exampleArray),
);

objectMirrorSubscribeListener keeps an object in sync in place. It’s empty while the doc doesn’t exist:

const doc = {};
const unsubscribe = await exampleCollection.subscribeOne(
docId,
objectMirrorSubscribeListener(doc),
);

arrayMirrorSubscribeListener empties the array first. These helpers can also take a subscribe listener as a second argument, allowing you to customize any of the listener callbacks.

A subscription lasts over connection losses. Once the connection is back, your listener gets onAdd, onChange and onDelete for what changed meanwhile, so a mirrored array or object catches up by itself.

All special field names and values that are used throughout Bazaar start with a $ sign. As such, we recommend not using field names or values that start with a $.

In documents, currently the only reserved value is "$now". On insert, update, and replace, the server turns it into the current time as an ISO 8601 UTC string, e.g. "2026-11-13T09:30:00.000Z". This gives you a consistent timestamp no matter which time zone the app runs in.

await exampleCollection.insertOne({ text: "Hi", createdAt: "$now" });

Filters can use the reserved value "$user", the calling user’s ID:

const myDocs = await exampleCollection.getAll({ authorId: "$user" });

You can filter the document queries with fine-grained control.

By default, filter values are checked for equality. The filter

const filter = {
isActive: true,
};

will return all documents where isActive === true.

Comparison operator can also be specified explicitly. The equality filter above would then look as follows:

const filter = {
isActive: { $eq: true },
};

Filters currently support the following comparison operators:

  • $eq: equal
  • $ne: not equal
  • $gt: greater than
  • $ge: greater than or equal
  • $lt: less than
  • $le: less than or equal
  • $in: the field equals one of the values in an array, e.g. { status: { $in: ["open", "pending"] } }
  • $startsWith: a string field starts with a prefix, e.g. { name: { $startsWith: "Sky" } }
  • $contains and $containsAny: an array field contains a value, see below
  • A value only matches values of the same type: { age: 30 } doesn’t match "30", and true doesn’t match 1. Comparing a number with a string never matches.
  • Strings compare character by character by Unicode code point, so "B" sorts before "a".
  • null matches documents where the field is null or missing: { deletedAt: null }.
  • $ne and $not select every document the filter they negate doesn’t, including documents without the field: { status: { $ne: "done" } } also returns documents with no status.
  • $contains and $containsAny only match array fields. $startsWith only matches string fields and is case-sensitive.
  • a.b filters on field b of object field a, tags[0] on the first element of tags.

An invalid filter fails with a BadRequest error that names the problem, e.g. an unknown operator such as $gte, or an array as a value. A filter can have at most 200 terms (keys, operators and $containsAny values), and a key at most 256 characters.

The $contains operator is used to check if an array field in the documents contains a specified value.

// Select documents where the 'tags' array field contains 'urgent'
const filter = {
tags: { $contains: "urgent" },
};

$containsAny checks if an array field contains at least one of the values:

// Select documents tagged 'urgent' or 'blocked'
const filter = {
tags: { $containsAny: ["urgent", "blocked"] },
};
// Select documents where `age` is greater than 30 and `isActive` is true
const filter = {
age: { $gt: 30 },
isActive: true,
};

For simple filters, this is enough. For more complex filtering queries you can also use the $and key:

// Select documents where `age` is greater than 30 and `isActive` is true
const filter = {
$and: [{ age: { $gt: 30 } }, { isActive: true }],
};
// Select documents where `status` is either 'pending' or 'completed'
const filter = {
$or: [{ status: "pending" }, { status: "completed" }],
};
// Select documents where `category` is not 'archived'
const filter = {
$not: { category: "archived" },
};
// Select documents where `manager` is 'John' and either `yearsOfExperience` is greater than 5 or (`department` is 'HR' and `location` is 'New York')
const filter = {
manager: "John",
$or: [
{ yearsOfExperience: { $gt: 5 } },
{ $and: [{ department: "HR" }, { location: "New York" }] },
],
};

And for a more complex example:

/**
* Select documents where either `height` is between 80 and 140 (exclusive)
* or `weight` is between 10 and 25 (exclusive), and additionally, `age` is less than 55.
*/
const filter = {
$or: [
{
height: {
$gt: 80,
$lt: 140,
},
},
{
weight: {
$gt: 10,
$lt: 25,
},
},
],
age: { $lt: 55 },
};

The orderBy option allows you to sort the results fetched from a collection using the getAll or getPage methods. By defining the order criteria for one or more fields, you can organize the returned documents according to specific requirements.

orderBy is an object where each key represents a field name to sort by, and the value is either OrderByType.ASC ("asc") for ascending order or OrderByType.DESC ("desc") for descending order.

You can sort by single or multiple fields, specifying the order for each field individually:

// Sorting by 'height' in descending order, then by 'age' in ascending order
const orderBy = { height: OrderByType.DESC, age: OrderByType.ASC };
const sortedDocs = await exampleCollection.getAll(filter, { orderBy });

How documents sort:

  • Ties on every orderBy field are broken by id, ascending. Without orderBy, documents come in id order.
  • Documents missing the field, or with null, come first in ascending order and last in descending order.
  • A field holding different types sorts numbers first, then strings, booleans, arrays and objects.
  • Strings sort by Unicode code point, so "B" comes before "a".
  • Nested fields work like in filters: { "address.city": OrderByType.ASC }.

Generally, collections are created lazily and don’t need additional management. However, in some cases manually creating, dropping, or listing collections is useful.

Create collections manually using the bzr.collections.create method.

const message = await bzr.collections.create("example-collection-name");

Drop, or delete, a collection, all of its docs, and its permissions.

const message = await bzr.collections.drop("example-collection-name");

List the names of all collections.

const collectionsNames = await bzr.collections.list();