Skip to content

@latticecms/store-mongo

The MongoDB CollectionStore for @latticecms/core. Each collection is a Mongo collection of the same name, and a document’s id is its _id. Filters translate one to one into Mongo queries, and the store passes the conformance suite every Lattice store passes. It also runs the app’s data migrations, and the relay that publishes the events an outbox stores.

Status: before 1.0.

Terminal window
npm install @latticecms/store-mongo @latticecms/core hexok @ts-pf/contract @ts-pf/protocol @ts-pf/server @ts-pf/docs @ts-pf/mcp zod @hexok/logger @opentelemetry/api

@latticecms/core, hexok, zod, @hexok/logger and @opentelemetry/api are peer dependencies, shared with the app for the reasons core’s README gives. Install core’s own peers too, as above. The mongodb driver is this package’s own dependency: the store owns its client. Upgrade store-mongo and core in one npm install, then check for one copy of core, as core’s README shows.

The tests run against MongoDB 8.0. Transactions need a replica set or a sharded cluster; see Transactions.

Create the store. The crm reads its settings in one place, for the server, the worker and its scripts:

examples/crm/src/infra/store.ts
export function mongoStore(env: NodeJS.ProcessEnv): MongoStore {
const url = env.MONGODB_URL;
if (url === undefined) throw new Error('Set MONGODB_URL');
return new MongoStore({ url, database: env.MONGODB_DATABASE ?? 'crm' });
}

Start it, migrate, create the indexes, then serve:

examples/crm/src/servers/http/server.ts
const crm = createApp({ store, events: deps.events });
await store.start();
await migrate(store, migrations, { logger });
await crm.ensure();

On shutdown, stop the server taking requests, then the store:

examples/crm/src/servers/http/server.ts
await server.close();
await store.stop();

new MongoStore({ url, database, client? }) (MongoStoreOptions) takes a connection string, the database every collection lives in, and MongoClientOptions for its client. serverSelectionTimeoutMS bounds how long start() waits for the server.

The store owns its MongoClient.

  • start() connects and pings the server. A start() while one is pending joins it. A start() after stop() opens a new client. A failed start closes its client, and a later start() begins clean.
  • stop() closes the client. A pending start() rejects with Stopped.
  • A call before start() rejects with MongoStoreError NotStarted, during it with Starting, and after stop() with Stopped. These are the codes of hexok’s Redis adapters, so an app matches every adapter on error.code. They mean the call came at the wrong time: fix the call order, and do not retry.

Start the store before the app serves traffic, and stop it after the server closes.

Lattice uses store.transaction(work) for a delete that cascades or nullifies refs, for a relation’s set, and for an app’s own transaction. With an outbox, it uses one for every generated write.

  • On a replica set or a mongos, work runs in one Mongo transaction, with a view of the store whose every call carries the session. It commits, or on a throw writes nothing. The driver’s withTransaction may run work again on a transient error.
  • The driver does not support calls at the same time in a transaction, so MongoStore runs them one at a time, in the order they were made. Promise.all works anywhere in work, and is no faster than awaiting each call. When work ends, calls already made finish first, and a later one throws. So none joins a retry. This covers only the store’s calls: await each call that uses a session of your own before the next one.
  • Do not change a call’s arguments until it settles, in a transaction or outside one. Each call builds its filter, update or document when it is made, and copies a filter’s in and nin lists. It does not copy any other nested object or array.
  • Await a nested transaction. Its work is not a call, so the outer one does not wait for it, and can commit only part of it.
  • When a call on the store fails, let work fail too. Do not catch the error and carry on: the driver may run work again and again.
  • A transaction reads from the primary, whatever read preference the client sets, because MongoDB refuses any other there. The client’s read concern still applies, and MongoDB allows only local, majority and snapshot in a transaction. With an outbox, a client set to available or linearizable fails every generated write. So does one with write concern w: 0, which the driver refuses in a transaction.
  • A standalone server has no transactions, so there work runs in order, on the store itself, without atomicity. Lattice’s deletes write the parent last, so a failure partway leaves the parent in place, and the children already changed stay changed. Run production on a replica set; a single-node replica set is enough.
  • An index is never built inside a transaction, so ensure starts at once and is not part of one. Do not await it in work: a new index waits for a transaction that has read or written the collection.

A write concern says how many members must have a write before MongoDB confirms it. For repo writes and transactions, MongoStore uses the one in url or client. If neither sets one, MongoDB’s default applies. The relay and migrate() wait for a majority for some of their own writes.

MongoDB’s default is not always majority. It is w: 1 on a replica set with two data members and an arbiter, for example. MongoDB’s rule covers other sets with arbiters, and an administrator can set another default. With w: 1, a failover can undo a write that succeeded. That includes a committed transaction and a number from next.

Before the app does something outside the database that it cannot undo, such as deleting a file, wait for a majority to confirm what it relies on.

If it relies on a write, set this on the store that makes the write, and act only after the call or the transaction resolves:

new MongoStore({ url, database, client: { writeConcern: { w: 'majority' } } });

If it relies on a read, such as one that finds no row with a file’s key, that is not enough. Whatever the write concern, a read with MongoDB’s default read concern, local, can see a write or a removal that a failover can still undo. A majority read outside a transaction can miss a new row that no majority has yet. Read in a transaction, on a store with both settings, through the repos that work receives. Other repos do not join it, so nothing waits for a majority. Act only after the transaction resolves. If it throws, do not act:

new MongoStore({
url,
database,
client: {
readConcern: { level: 'majority' },
writeConcern: { w: 'majority' },
},
});
  • With these settings, w replaces the one in url. The URL’s journal and wtimeoutMS still apply.
  • readConcernLevel in url replaces the readConcern above, so remove it or set it to majority.
  • Set w itself. With only journal or wtimeoutMS, ordinary writes use the server’s default w, which can be 1. The driver adds w: 'majority' only to a transaction’s commit.
  • While no majority can confirm it, a write outside a transaction waits. wtimeoutMS limits the wait, and the call then fails. The timeout does not undo the write, but a failover still can.
  • wtimeoutMS also limits each wait for a commit. If a write concern is set without it, the driver uses 10 seconds. If none is set, the driver sends no limit with the first commit. After a timeout, the driver sends the commit again. It can also run work again, such as after a failover undoes the transaction. It stops starting these retries about two minutes after the transaction call began. If the call then fails, the transaction may still have committed.
  • After one of these errors, or a lost connection, the write may or may not be there, and a failover may still undo it. Do nothing outside the database that relies on the write, or on its absence.

repos.tickets.next('number', scope) counts in the _sequences collection, with one document for each counter. Each call is one findOneAndUpdate with $inc, which creates the counter on its first call. Core’s README has the recipe.

Counter _id value
A tenanted collection’s field JSON.stringify(['tickets.number', tenantId]) The last number given
A global collection’s field JSON.stringify(['tickets.number']) The last number given
  • In a transaction, the count commits or rolls back with it. After a rollback, another call can get the same number. On a standalone server nothing rolls back, so an insert that fails leaves a gap.
  • A counter is one document. Transactions that count on the same one at the same time conflict, and the driver runs all but one again. So keep them short.
  • Inside a transaction, call next only on the repos it gives. A call on the outer repos is not part of the transaction, and it can wait for a transaction that has already counted on the same counter.
  • Core refuses a collection whose slug starts with _, so none can be _sequences.
  • Trying again after a CONFLICT cannot fix a counter that was never started: each rollback gives the number back. If old code that does not use next writes documents after the switch, stop writes and start the counters again. Use a new migration, because migrate() does not run an applied one again.

next starts at 1 and does not look at the documents. When documents already have numbers, such as after an import, a migration starts each counter at the highest one, with no writes to the app while it runs. In up:

type Counter = { _id: string; value: number };
const used = db.collection('tickets').aggregate<Counter>([
{ $match: { number: { $type: 'number' } } },
{ $group: { _id: '$organizationId', value: { $max: '$number' } } },
]);
for await (const { _id: organizationId, value } of used) {
await db.collection<Counter>('_sequences').updateOne(
{ _id: JSON.stringify(['tickets.number', organizationId]) },
{ $max: { value } },
{ upsert: true },
);
}

$max never lowers a counter, so it is safe to run again. Every document needs a number first. The crm’s 0003-number-deals.ts numbers documents that have none, from the same counters.

With build({ events: outbox(DomainEvents) }), core stores each event in _outbox, in the write’s own transaction. OutboxRelay publishes each one, then deletes it. Core’s README says what an outbox promises, and how to move an app to one. The crm runs the relay in its worker:

examples/crm/src/servers/worker/main.ts
// Last, so each handler is already reading when an event is published.
const relay = new OutboxRelay({
store,
publish: publishTo(domainQueue),
logger: logger.child({ component: 'outbox' }),
});
await relay.start();

publish sends one event on. Here it goes to a queue, on a topic named by the event’s token, with its id beside its payload:

examples/crm/src/infra/events/domain-event-queue.ts
export function publishTo(
queue: Queue,
): (message: OutboxMessage) => Promise<unknown> {
return ({ id, token, payload }) => {
const queued: z.input<typeof QueuedEvent> = { id, payload };
return queue.publish(token, queued);
};
}

The subscriber takes the payload out again before it builds the event. See the crm’s subscribe.ts.

new OutboxRelay({ store, publish, logger, pollMs? }) (OutboxRelayOptions):

  • store is the app’s MongoStore. Start it before the relay. start() rejects with MongoStoreError when it is not started.
  • publish receives an OutboxMessage, { id, token, payload, createdAt }. payload is parsed from JSON and not validated, so handlers still validate it. The id is the same each time the event is published.
  • pollMs is how long the relay waits before it looks again, 500 by default. After a full batch of 100 it looks again at once.

On shutdown, stop the relay first, then what publish uses, then the store. stop() waits for the event being published, for up to 10 seconds, and for its database calls, then tries to release the lease. With MongoDB down, those calls can take as long as the driver’s own timeouts. With a primary but no majority, its writes wait for the majority with no limit, so stop() can outlast a deploy’s grace period. start() returns before the relay holds the lease. One called during a stop() waits for it, and starts nothing if stop() is called again meanwhile.

  • At least once. The event stays stored until publish resolves. If the relay stops between that and the delete, the event is published again, with the same id.
  • publish has 10 seconds. One that takes longer counts as failed and is tried again. The call is not cancelled, so it may still arrive, as a repeat. A Redis client can hold its commands through an outage, and without the limit one call would block the relay and stop().
  • A failed event is retried forever, after 1 second, then 2, doubling to 1 minute. Each failure logs an error. Watch for events whose attempts keeps growing: one that publish always refuses stays in _outbox until it succeeds or you delete it.
  • An event that already failed does not stop new ones. Each pass reads events that never failed, oldest first, then failed ones that are due. It leaves each of the two lists at its first failure, so an outage costs about two failed calls a pass. New events that all fail do hold up the ones behind them: each pass gets past one, so about two a second by default. If each times out, it is about one every 20 seconds, because each pass also waits for a retry that times out. A retry that times out also delays new events: by up to 10 seconds, and a backlog moves at most 100 events for each such retry. Order is approximate.
  • One relay works at a time, under a 30-second lease in _outbox_lock. Run one in each worker process: the others wait. One takes over when the active relay stops, or within about 30 seconds of a crash. A relay tries to release its lease when it stops, and one it cannot release expires. A relay that loses its lease starts no more publishes, even after its process was suspended. One in progress can finish, so that event can be published twice.
  • It reads from the primary, with read concern majority. A failover cannot undo a write after its event is out. Its own writes to _outbox wait for a majority too, whatever write concern the app’s client sets, so it does not read a row it has deleted and publish it again. Each delete waits for that write, and the relay publishes one event at a time. Writes to its lease wait for a majority too.
  • Payloads are not encrypted. They are plain JSON in _outbox, and publish receives them as they are. Core’s README says what to do with an event that carries a secret.
  • After a database error, it logs the error’s name, tries to release its lease, waits a second and tries again.
  • On a standalone server it works, and warns at start: there are no transactions there, so a crash can lose an event.

build().ensure() creates one index, { retryAt, createdAt, position }, which serves both reads.

Log Level Fields
outbox relay active info
outbox relay waiting for another info heldSince, when known
outbox relay lost its lease warn
outbox relay: this MongoDB server has no transactions, so a crash can lose an event warn
outbox publish: a publish failed error id, token, attempts, error
outbox relay: a database error error error

error is the error’s name only, such as TimeoutError. A log never holds a payload or an error’s message, which can quote a document.

  • where translates operator by operator: eq, ne, in, nin, gt, gte, lt and lte become their $ operators. contains is a case-insensitive regex with every metacharacter escaped. exists: true is { $ne: null } and exists: false is { $eq: null }, because in Lattice null does not exist. and and or become $and and $or.
  • Filters are combined with $and, never merged into one object, so a filter on id cannot replace the call’s own id match.
  • find sorts by the sort keys and then _id, and applies the cursor as one more filter. A document with no value for a sort field comes last in either direction. Mongo already sorts a missing or null value last on a descending key, so a sort with no ascending optional key is a plain, index-served sort. When the first key is the one ascending optional key, find runs two queries: documents with a value, which an index on the field serves, then, only when that page is not full, documents without one. Any other ascending optional key sorts through an aggregate with a computed key, which cannot use an index for the sort.
  • A duplicate key on insert or update, from the id or a unique index, is Lattice’s CONFLICT with { collection, id, fields }: id is the document being written, and fields are the clashing index’s keys from the error’s keyPattern, with _id as id. A server that leaves keyPattern out, as some MongoDB-compatible services do, gives fields: [].
  • ensure(collection, indexes) creates each index with createIndex and never drops one. An index with present gets a partialFilterExpression that matches each listed field by $type: every type but null, array and the deprecated ones, such as undefined. On an array field, $type matches by element, so [] and [null] are left out. build().ensure() calls it for every collection that declares indexes. MongoStore never names an index, so MongoDB gives it the default name, such as email_1. An existing index under that name that differs throws an Error that names it. An index with the declared keys and identifying options counts as ensured, under another name or with options Lattice does not declare, such as a TTL or hidden. An index under another name with the same keys and other options is left alone, and the declared one is created beside it. A unique index over existing duplicates throws a MongoStoreCallError with code 11000 that names the index’s fields, not the duplicate values. Changing an index is a migration: drop the old one there, and ensure() creates the new one.
  • count is countDocuments.
  • countBy is one aggregation: $match, a $project that turns the field into its keys (each distinct element of an array, or null for a missing value or []), $unwind, $group, $sort by count and key, and $limit one past the limit, to tell whether there are more.
  • has is equality on the array field, which Mongo matches against any element. nhas is $ne, which matches when no element is equal, and matches a missing or null array.

A data migration changes stored documents once, such as backfilling a new field. Mongo has no schema to migrate; a breaking field change is a data migration. Migrations run forward only: a bad one is fixed by a new one.

examples/crm/src/infra/migrations/0001-backfill-deal-archived.ts
import type { Migration } from '@latticecms/store-mongo';
/**
* Deals written before `archived` existed have no such field, and the read
* filter `archived: { eq: false }` would hide them. Every organization's
* deals: a migration is system work, outside access and tenancy. The
* filter skips the deals already done, so a second run changes nothing.
*/
export default {
id: 1,
name: 'backfill-deal-archived',
async up({ db, logger }) {
const { modifiedCount } = await db
.collection('deals')
.updateMany(
{ archived: { $exists: false } },
{ $set: { archived: false } },
);
logger.info('deals backfilled', { modifiedCount });
},
} satisfies Migration;

up receives { db, session?, signal, logger }. db is the store’s raw Mongo database, because a migration reads documents in their old shape, which the collection’s types no longer describe. logger is a child with the migration’s id and name. The types are Migration, MigrationContext (what up receives), MigrateOptions and Ran.

The app lists its migrations explicitly, in id order:

examples/crm/src/infra/migrations/index.ts
import m0001 from './0001-backfill-deal-archived.js';
import m0002 from './0002-backfill-membership-name.js';
import m0003 from './0003-number-deals.js';
/** The app's data migrations, in id order. `migrate()` runs each once. */
export const migrations = [m0001, m0002, m0003];

At startup, start the store, then migrate, then create indexes, as in Wiring. A migration can fix duplicates before a unique index is built, and drop an index the app changed, which ensure() never does. A migration that needs an index of its own creates it with db.collection(name).createIndex().

migrate(store, migrations, { logger, lock? }) runs each pending migration once, in order, and returns { ran }: each { id, name, durationMs } that ran. Each one that runs is recorded in _migrations with its id, name, ranAt and durationMs, and logs one line with id, name and durationMs. When nothing is pending, it logs migrations up to date.

  • The list is checked first. Ids run 1, 2, 3 … in list order. A gap, a duplicate, a recorded migration missing from the list, or a recorded one with another name throws a MigrationError (Gap, Duplicate, Unknown, Renamed) before any migration runs. File names such as 0002-rename-stage.ts are a convention; the runner reads id and name.

  • Pending means no record. A migration runs when its id has no record in _migrations. Deleting a record runs that migration again on the next run, after the later ones that already ran, so its up must handle the shape they left.

  • A failure stops the run. The migration is not recorded, its error passes through after one error log line, and the next run starts again at that migration. up uses the raw database, so that error can be the driver’s own and quote stored data. It can appear wherever the error is printed: that log line, and an app’s own, such as console.error at startup. So write up to be safe to run twice. Filter on what is not done yet, as the CRM’s backfill does with archived: { $exists: false }.

  • Transactions are opt-in. With transaction: true, up gets a session, and its writes and its record commit together or not at all. Pass { session } to every write, and await each call that uses it before the next one, because the driver does not support calls at the same time in a transaction. So do not use it in a Promise.all. It reads from the primary and commits with write concern majority, whatever the client sets. It needs a replica set, or the run throws NoTransactions before anything runs. A long migration can exceed Mongo’s transaction limits, which is why it is not the default. The driver may run a transaction’s callback again on a transient error, which up handles, since it is safe to re-run.

  • Records are read and written on the primary, with a majority, whatever the client sets. With a stale record, or one that a failover undid, a migration would run again.

  • One process at a time. A lease in _migrations_lock keeps two processes from migrating together. It is taken on the server’s clock, renewed every third of lock.ttlMs (60 s by default), and released by a token, so a process never releases another’s lease. Its writes wait for a majority, whatever write concern the client sets. A process counts the lease from when it asked for it or renewed it, and stops a margin before it ends. It does not use a lease whose answer came too late. It measures time on two clocks and takes the longer, so setting the system clock back does not extend a lease. Setting it forward can end one early: a migration then stops with LockLost, unrecorded, and a wait can reach waitMs early. A lease whose holder died, or could not release it, expires and is taken over. A second process logs migrations waiting for lock, waits up to lock.waitMs (10 minutes by default), and then finds nothing left to run; past waitMs it rejects with LockTimeout. It checks waitMs between its database calls, so a call that stalls can make it wait longer. With a primary but no majority, migrate() waits for the majority with no limit, even when the client sets w: 1. If the lease is lost or cannot be renewed in time while a migration runs, signal aborts, and the run stops with LockLost without recording that migration. Pass signal to long loops. Nothing can stop an up that is already running: after its process was suspended past the lease, it can overlap another process’s run until it sees signal. The run checks the lease again just before it records a migration, and before the driver runs a transaction again. This is another reason to write up to be safe to run twice.

An app that migrates before it starts, rather than at startup, runs npx lattice migrate from @latticecms/cli after its build. It imports a built module that exports the store, not started, and the list; the crm’s is built from:

examples/crm/src/servers/scripts/migrate.ts
export const store = mongoStore(process.env);
export { migrations };

The command starts the store, runs migrate() with a ConsoleLogger, stops the store, and exits 1 on a MigrationError. Its output is migrate()’s log. An app’s own script can call migrate() instead. lattice migration <name> writes the next migration and appends it to the list; its up() throws until it is written, so an unwritten migration is never recorded as done.

A process can then refuse to start on a database that was not migrated. pendingMigrations(store, migrations) returns each listed migration with no record in _migrations, as { id, name }, in id order. It runs migrate()’s checks of the list and of the records, so a bad list fails at startup too. It reads the records the same way, takes no lock and writes nothing. The store must be started.

await store.start();
const pending = await pendingMigrations(store, migrations);
if (pending.length > 0) {
throw new Error(`${pending.length} migrations pending: run migrate`);
}

A migration counts as pending until its record is written, so a process that starts while migrate() runs refuses to start.

Each store call is one OpenTelemetry client span, a child of the active span, through @opentelemetry/api. With no SDK registered it is a no-op. The tracer is @latticecms/store-mongo.

  • The span is named {operation} {collection}, such as find deals, after the Mongo command the call runs: find (find, get, getMany), aggregate (count, countBy), insert, findAndModify (update, remove, next) and createIndexes (ensure). A next span’s collection is _sequences.
  • Attributes: db.system.name (mongodb), db.namespace (the database), db.operation.name and db.collection.name.
  • A transaction is one transaction span, and the calls in it are its children.
  • Migrations and the outbox relay use the driver directly, so their own calls make no spans.
  • A failed call sets status ERROR and error.type: Lattice’s code, such as CONFLICT, the driver’s error’s name, such as MongoServerError, or, when an app’s own error ends a transaction, that error’s name. It records no exception event, and neither do the use case and procedure spans above it. Their error.type is the name of the error they see, the MongoStoreCallError.
  • There is no db.query.text. A Mongo filter has no parameters, so its text would carry the values it matches.
Error Code When
LatticeError CONFLICT A duplicate key on insert or update, from the id or a unique index. data is { collection, id, fields }: the document being written and the clashing index’s fields, or [] when the error has no keyPattern. The driver’s message is never parsed or sent
MongoStoreCallError the driver’s, such as 11000 Any other call that fails in the driver. See below
MongoStoreError NotStarted, Starting, Stopped A call before start(), during it, or after stop(). Fix the call order; do not retry
MigrationError Gap, Duplicate, Unknown, Renamed The migration list does not match itself or what ran. Thrown before any migration runs
MigrationError NoTransactions A migration asks for a transaction on a deployment without them. Thrown before any migration runs
MigrationError LockTimeout, LockLost Another process held the lock past waitMs, or the lease was lost while a migration ran

Each but MongoStoreCallError is a hexok Errors catalog, so MongoStoreError.is(error) and error.code narrow it. Each is a failure, not a refusal: a use case logs it at error and its spans record ERROR. Leave them out of family({ refusals }). MongoStoreCallError, a plain Error, is a failure too. Of these, only the lifecycle catalog MongoStoreError was ever logged as a refusal, before store-mongo 0.18.0.

A MongoStoreCallError carries no stored or queried value. A driver’s error can quote a document or a filter in its message, its stack and its errorResponse, and an error reaches logs and spans. So the store’s calls never throw it, ensure() and transaction included. They throw this instead:

MongoStoreCallError: MongoStore: insert users failed with MongoServerError (121). The driver's message is left out, because it can quote stored or queried values.
  • The message has the Mongo command, the collection, and the driver’s error name and code, if it has one. An error that is not the driver’s or BSON’s is TypeError, RangeError or Error, with no code. For ensure(), it has the index’s fields too. For a commit, it says transaction. For code 171, it says cannot index parallel arrays, as MemoryStore does.
  • driverError, code and errorLabels are properties. There is no cause and no errorResponse.
  • A transaction whose commit result is unknown, such as after a lost connection or a write concern timeout, throws one with errorLabels including UnknownTransactionCommitResult, after the driver’s own retries. The transaction may have committed. A throw without the label does not prove it did not. A single write outside a transaction may also have been written when it throws.
  • It is an ordinary Error, so a failed call is logged as an error and fails its spans, where a catalog error is a refusal. The class is not exported. Check error.name === 'MongoStoreCallError'.
  • In a transaction, work sees the MongoStoreCallError. When work throws that same error, the driver gets its own, so it retries as it would without Lattice. It does not retry for another error made from it, or for one from a second loaded copy of this package. What work throws comes out of transaction as it was, an app’s own error too.
  • start() throws the driver’s own error: it connects, and reads and writes no documents.
  • migrate() and a migration’s up do too. See Migrations.
  • The app’s own driver calls throw the driver’s errors, and BSON’s. A logger that cleans them by name must match both Mongo… and BSON…, such as BSONError. Both can quote stored or queried values, and BSON’s can quote a field’s name too.

Both follow MongoDB’s null and missing rules, and both pass the same conformance suite. Both keep a value as JSON would: a key set to undefined is left out, at any depth, and an undefined array element is null. Two differences remain, and the suite does not cover them:

  • String order. MongoDB compares strings by their UTF-8 bytes, which is code point order. JavaScript compares UTF-16 code units. They agree on everything except U+E000–U+FFFF against characters above U+FFFF, which sort the other way. ASCII and ISO timestamps sort the same.
  • Case folding in contains. MongoDB’s case-insensitive regex and JavaScript’s toLowerCase can disagree outside ASCII, such as for ß and the Turkish İ.

store-mongo follows semver from 1.0, as core does (0058). Its peer range on core moves with core’s majors.

  • Its exports, with the signatures this README shows: MongoStore, migrate, pendingMigrations, OutboxRelay, MongoStoreError, MigrationError, and their option and result types.

  • MongoStoreCallError, which is not exported: its name, and its driverError, code and errorLabels, as Errors describes.

  • Data on disk. A 1.x release reads what 1.0 wrote:

    Collection Document
    An app’s collection, and a relation’s through The collection’s name is its slug. A document is { _id, ...fields }: _id is its id, a string, and every other field is stored under its own name, as its schema’s output. createdAt and updatedAt are ISO strings, as is any date field, since a schema cannot hold a Date. A key set to undefined is left out, at any depth, and an undefined array element is null (0059). A tenant field is an ordinary field
    _outbox { _id, token, payload, createdAt, position, attempts?, retryAt? }: _id is the event’s id, payload a JSON string, and createdAt and retryAt ISO strings. The relay hands publish an OutboxMessage, { id, token, payload, createdAt }; any envelope around it, such as the crm’s { id, payload }, is the app’s
    _outbox_lock, _migrations_lock A lease, { _id, token, acquiredAt, expiresAt }, with dates as BSON dates. _id is 'relay' and 'migrations', so an old and a new process share one lock
    _migrations { _id, name, ranAt, durationMs }: _id is the migration’s number, and ranAt a BSON date
    _sequences { _id, value }, with the _id layout in Sequences
  • Read and write concerns are the client’s (0055). For repo calls and transactions, set them in url or client; MongoStore keeps the driver’s default and has no option of its own. The relay and migrate() wait for a majority on their own bookkeeping, as Write concern says. First-class options can come in a minor. A change of default would be a major.

  • Indexes. For an unchanged collection definition, the indexes ensure() builds keep their keys, options and names within a major. Since ensure() never drops an index and throws on one that differs, a change would stop every app with an existing database at startup. They are:

    • each index the collection declares, its keys in their declared order, with unique and present (a partialFilterExpression by $type) as Queries describes;
    • for each ref, a lookup index: the tenant field, if any, then the ref field. It is left out when a declared index without present starts with those keys, and gains _id when a declared present index has exactly them;
    • for each relation’s through collection: a unique index on the tenant field, if any, the parent field and the target field, and one on the tenant field and the target field;
    • for _outbox, { retryAt: 1, createdAt: 1, position: 1 }.

    Each takes the name MongoDB gives its keys. id is _id in keys.

  • These behaviors: MongoStore runs a transaction’s calls one at a time, in the order they were made; ensure() throws an Error that names an existing index that differs, with no cause; the relay delivers at least once, with the same id each time; a standalone server works, without transactions.

  • Dependencies and runtimes: peers @latticecms/core, hexok ^2.3.1, zod ^4.1.0, @hexok/logger ^0.2.0 and @opentelemetry/api ^1.3.0. Node and TypeScript follow core’s windows (0058). MigrationContext.db is the driver’s Db, and MigrateOptions.logger and the relay’s logger are @hexok/logger’s. The mongodb driver is a dependency, ^7.9.1; its next major is a major here.

  • Span names and attributes, log messages and fields, including the relay’s log table, and the text of any error message.
  • How a Where or Sort becomes a query or an aggregation, beyond what this README promises.

None.

The package’s tests run on mongodb-memory-server: one single-node replica set and one standalone server per run, started in vitest’s globalSetup, and a fresh database per test. The standalone server runs the conformance cases that need no transactions. The lease tests measure time closely, so vitest.config.ts runs them after the other files. Nothing needs to be installed. The first run downloads mongod (about 100 MB) into ~/.cache/mongodb-binaries, and later runs reuse it. The server version is pinned in package.json (config.mongodbMemoryServer.version), and MONGOMS_VERSION overrides it. Linux on musl, such as Alpine, has no mongod build.