@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.
Install
Section titled “Install”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.
Wiring
Section titled “Wiring”Create the store. The crm reads its settings in one place, for the server, the worker and its scripts:
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:
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:
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.
Lifecycle
Section titled “Lifecycle”The store owns its MongoClient.
start()connects and pings the server. Astart()while one is pending joins it. Astart()afterstop()opens a new client. A failed start closes its client, and a laterstart()begins clean.stop()closes the client. A pendingstart()rejects withStopped.- A call before
start()rejects withMongoStoreErrorNotStarted, during it withStarting, and afterstop()withStopped. These are the codes of hexok’s Redis adapters, so an app matches every adapter onerror.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.
Transactions
Section titled “Transactions”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,
workruns 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’swithTransactionmay runworkagain on a transient error. - The driver does not support calls at the same time in a transaction, so
MongoStoreruns them one at a time, in the order they were made.Promise.allworks anywhere inwork, and is no faster than awaiting each call. Whenworkends, 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
inandninlists. It does not copy any other nested object or array. - Await a nested
transaction. Itsworkis 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
workfail too. Do not catch the error and carry on: the driver may runworkagain 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,majorityandsnapshotin a transaction. With an outbox, a client set toavailableorlinearizablefails every generated write. So does one with write concernw: 0, which the driver refuses in a transaction. - A standalone server has no transactions, so there
workruns 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
ensurestarts at once and is not part of one. Do not await it inwork: a new index waits for a transaction that has read or written the collection.
Write concern
Section titled “Write concern”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,
wreplaces the one inurl. The URL’sjournalandwtimeoutMSstill apply. readConcernLevelinurlreplaces thereadConcernabove, so remove it or set it tomajority.- Set
witself. With onlyjournalorwtimeoutMS, ordinary writes use the server’s defaultw, which can be 1. The driver addsw: 'majority'only to a transaction’s commit. - While no majority can confirm it, a write outside a transaction waits.
wtimeoutMSlimits the wait, and the call then fails. The timeout does not undo the write, but a failover still can. wtimeoutMSalso 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 runworkagain, 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.
Sequences
Section titled “Sequences”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
nextonly 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
CONFLICTcannot fix a counter that was never started: each rollback gives the number back. If old code that does not usenextwrites documents after the switch, stop writes and start the counters again. Use a new migration, becausemigrate()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.
The outbox relay
Section titled “The outbox relay”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:
// 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:
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):
storeis the app’sMongoStore. Start it before the relay.start()rejects withMongoStoreErrorwhen it is not started.publishreceives anOutboxMessage,{ id, token, payload, createdAt }.payloadis parsed from JSON and not validated, so handlers still validate it. The id is the same each time the event is published.pollMsis 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
publishresolves. If the relay stops between that and the delete, the event is published again, with the same id. publishhas 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 andstop().- A failed event is retried forever, after 1 second, then 2, doubling to 1 minute. Each failure logs an error. Watch for events whose
attemptskeeps growing: one thatpublishalways refuses stays in_outboxuntil 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_outboxwait 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, andpublishreceives 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.
Queries
Section titled “Queries”wheretranslates operator by operator:eq,ne,in,nin,gt,gte,ltandltebecome their$operators.containsis a case-insensitive regex with every metacharacter escaped.exists: trueis{ $ne: null }andexists: falseis{ $eq: null }, because in Lattice null does not exist.andandorbecome$andand$or.- Filters are combined with
$and, never merged into one object, so a filter onidcannot replace the call’s own id match. findsorts 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,findruns 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
insertorupdate, from the id or a unique index, is Lattice’sCONFLICTwith{ collection, id, fields }:idis the document being written, andfieldsare the clashing index’s keys from the error’skeyPattern, with_idasid. A server that leaveskeyPatternout, as some MongoDB-compatible services do, givesfields: []. ensure(collection, indexes)creates each index withcreateIndexand never drops one. An index withpresentgets apartialFilterExpressionthat matches each listed field by$type: every type but null, array and the deprecated ones, such as undefined. On an array field,$typematches 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 asemail_1. An existing index under that name that differs throws anErrorthat 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 orhidden. 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 aMongoStoreCallErrorwith code 11000 that names the index’s fields, not the duplicate values. Changing an index is a migration: drop the old one there, andensure()creates the new one.countiscountDocuments.countByis one aggregation:$match, a$projectthat turns the field into its keys (each distinct element of an array, ornullfor a missing value or[]),$unwind,$group,$sortby count and key, and$limitone past the limit, to tell whether there are more.hasis equality on the array field, which Mongo matches against any element.nhasis$ne, which matches when no element is equal, and matches a missing or null array.
Migrations
Section titled “Migrations”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.
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:
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 as0002-rename-stage.tsare a convention; the runner readsidandname. -
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 itsupmust 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.
upuses 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 asconsole.errorat startup. So writeupto be safe to run twice. Filter on what is not done yet, as the CRM’s backfill does witharchived: { $exists: false }. -
Transactions are opt-in. With
transaction: true,upgets asession, 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 aPromise.all. It reads from the primary and commits with write concernmajority, whatever the client sets. It needs a replica set, or the run throwsNoTransactionsbefore 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, whichuphandles, 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_lockkeeps two processes from migrating together. It is taken on the server’s clock, renewed every third oflock.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 withLockLost, unrecorded, and a wait can reachwaitMsearly. A lease whose holder died, or could not release it, expires and is taken over. A second process logsmigrations waiting for lock, waits up tolock.waitMs(10 minutes by default), and then finds nothing left to run; pastwaitMsit rejects withLockTimeout. It checkswaitMsbetween 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 setsw: 1. If the lease is lost or cannot be renewed in time while a migration runs,signalaborts, and the run stops withLockLostwithout recording that migration. Passsignalto long loops. Nothing can stop anupthat is already running: after its process was suspended past the lease, it can overlap another process’s run until it seessignal. 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 writeupto be safe to run twice.
As a deploy step
Section titled “As a deploy step”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:
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.
Tracing
Section titled “Tracing”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 asfind deals, after the Mongo command the call runs:find(find, get, getMany),aggregate(count, countBy),insert,findAndModify(update, remove, next) andcreateIndexes(ensure). Anextspan’s collection is_sequences. - Attributes:
db.system.name(mongodb),db.namespace(the database),db.operation.nameanddb.collection.name. - A transaction is one
transactionspan, 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 asCONFLICT, the driver’s error’s name, such asMongoServerError, 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. Theirerror.typeis the name of the error they see, theMongoStoreCallError. - There is no
db.query.text. A Mongo filter has no parameters, so its text would carry the values it matches.
Errors
Section titled “Errors”| 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,RangeErrororError, with no code. Forensure(), it has the index’s fields too. For a commit, it saystransaction. For code 171, it sayscannot index parallel arrays, asMemoryStoredoes. driverError,codeanderrorLabelsare properties. There is nocauseand noerrorResponse.- A
transactionwhose commit result is unknown, such as after a lost connection or a write concern timeout, throws one witherrorLabelsincludingUnknownTransactionCommitResult, 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. Checkerror.name === 'MongoStoreCallError'. - In a transaction,
worksees theMongoStoreCallError. Whenworkthrows 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. Whatworkthrows comes out oftransactionas 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’supdo 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…andBSON…, such asBSONError. Both can quote stored or queried values, and BSON’s can quote a field’s name too.
Known differences from MemoryStore
Section titled “Known differences from MemoryStore”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’stoLowerCasecan disagree outside ASCII, such as forßand the Turkishİ.
Stability
Section titled “Stability”store-mongo follows semver from 1.0, as core does (0058). Its peer range on core moves with core’s majors.
Public
Section titled “Public”-
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: itsname, and itsdriverError,codeanderrorLabels, 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 throughThe collection’s name is its slug. A document is { _id, ...fields }:_idis itsid, a string, and every other field is stored under its own name, as its schema’s output.createdAtandupdatedAtare ISO strings, as is any date field, since a schema cannot hold aDate. A key set toundefinedis left out, at any depth, and anundefinedarray element isnull(0059). A tenant field is an ordinary field_outbox{ _id, token, payload, createdAt, position, attempts?, retryAt? }:_idis the event’s id,payloada JSON string, andcreatedAtandretryAtISO strings. The relay handspublishanOutboxMessage,{ id, token, payload, createdAt }; any envelope around it, such as the crm’s{ id, payload }, is the app’s_outbox_lock,_migrations_lockA lease, { _id, token, acquiredAt, expiresAt }, with dates as BSON dates._idis'relay'and'migrations', so an old and a new process share one lock_migrations{ _id, name, ranAt, durationMs }:_idis the migration’s number, andranAta BSON date_sequences{ _id, value }, with the_idlayout in Sequences -
Read and write concerns are the client’s (0055). For repo calls and transactions, set them in
urlorclient;MongoStorekeeps the driver’s default and has no option of its own. The relay andmigrate()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. Sinceensure()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
uniqueandpresent(apartialFilterExpressionby$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
presentstarts with those keys, and gains_idwhen a declaredpresentindex has exactly them; - for each relation’s
throughcollection: 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.
idis_idin keys. - each index the collection declares, its keys in their declared order, with
-
These behaviors:
MongoStoreruns a transaction’s calls one at a time, in the order they were made;ensure()throws anErrorthat names an existing index that differs, with nocause; 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.0and@opentelemetry/api^1.3.0. Node and TypeScript follow core’s windows (0058).MigrationContext.dbis the driver’sDb, andMigrateOptions.loggerand the relay’sloggerare@hexok/logger’s. Themongodbdriver is a dependency,^7.9.1; its next major is a major here.
Not public
Section titled “Not public”- Span names and attributes, log messages and fields, including the relay’s log table, and the text of any error message.
- How a
WhereorSortbecomes a query or an aggregation, beyond what this README promises.
Deprecations
Section titled “Deprecations”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.