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.
Using a Collection
Section titled “Using a Collection”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 collectionconst 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;};Use Another Owner’s Collection
Section titled “Use Another Owner’s Collection”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");Handle Lazy Collection Creation
Section titled “Handle Lazy Collection Creation”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
Section titled “Get all Docs”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 filterconst 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.
Get Docs by Page
Section titled “Get Docs by Page”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 Doc
Section titled “Get a Doc”Get a single doc.
const doc = await exampleCollection.getOne("example-doc-id");If no document with this ID exists, null is returned.
Insert a Doc
Section titled “Insert a Doc”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
Section titled “Update a Doc”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 a Doc
Section titled “Replace a Doc”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 Docs
Section titled “Delete All Docs”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 Doc
Section titled “Delete a Doc”Delete a specific document from a collection by its ID.
const message = await exampleCollection.deleteOne("example-doc-id");Subscribe to Collection Change Events
Section titled “Subscribe to Collection Change Events”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.
Subscribe Listener
Section titled “Subscribe Listener”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
onInitialfunction is provided, it will be called for each existing document in the collection. - The
onInitialcallback serves as a convenient alternative to manually fetching and iterating over all documents in a collection. onInitialis 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.
Subscribe to Doc Change Events
Section titled “Subscribe to Doc Change Events”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.
Subscribe Listener Helpers
Section titled “Subscribe Listener Helpers”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.
Connection Losses
Section titled “Connection Losses”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.
Reserved field names and values
Section titled “Reserved field names and values”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" });Filtering
Section titled “Filtering”You can filter the document queries with fine-grained control.
Comparison Operators
Section titled “Comparison Operators”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" } }$containsand$containsAny: an array field contains a value, see below
How Values Match
Section titled “How Values Match”- A value only matches values of the same type:
{ age: 30 }doesn’t match"30", andtruedoesn’t match1. Comparing a number with a string never matches. - Strings compare character by character by Unicode code point, so
"B"sorts before"a". nullmatches documents where the field isnullor missing:{ deletedAt: null }.$neand$notselect every document the filter they negate doesn’t, including documents without the field:{ status: { $ne: "done" } }also returns documents with nostatus.$containsand$containsAnyonly match array fields.$startsWithonly matches string fields and is case-sensitive.a.bfilters on fieldbof object fielda,tags[0]on the first element oftags.
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.
Filter with $contains Operator
Section titled “Filter with $contains Operator”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"] },};Filter with AND Conditions
Section titled “Filter with AND Conditions”// Select documents where `age` is greater than 30 and `isActive` is trueconst 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 trueconst filter = { $and: [{ age: { $gt: 30 } }, { isActive: true }],};Filter with OR Conditions
Section titled “Filter with OR Conditions”// Select documents where `status` is either 'pending' or 'completed'const filter = { $or: [{ status: "pending" }, { status: "completed" }],};Filter with NOT Condition
Section titled “Filter with NOT Condition”// Select documents where `category` is not 'archived'const filter = { $not: { category: "archived" },};Nested Filter Conditions
Section titled “Nested Filter Conditions”// 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 },};Ordering (Sorting)
Section titled “Ordering (Sorting)”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 orderconst orderBy = { height: OrderByType.DESC, age: OrderByType.ASC };const sortedDocs = await exampleCollection.getAll(filter, { orderBy });How documents sort:
- Ties on every
orderByfield are broken byid, ascending. WithoutorderBy, documents come inidorder. - 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 }.
Managing Collections
Section titled “Managing Collections”Generally, collections are created lazily and don’t need additional management. However, in some cases manually creating, dropping, or listing collections is useful.
Create a Collection
Section titled “Create a Collection”Create collections manually using the bzr.collections.create method.
const message = await bzr.collections.create("example-collection-name");Drop a Collection
Section titled “Drop a Collection”Drop, or delete, a collection, all of its docs, and its permissions.
const message = await bzr.collections.drop("example-collection-name");List Collections
Section titled “List Collections”List the names of all collections.
const collectionsNames = await bzr.collections.list();