Skip to content

Latest commit

 

History

History
343 lines (215 loc) · 14.6 KB

API.md

File metadata and controls

343 lines (215 loc) · 14.6 KB

API Reference

MongoLite

constructor(dbPathOrOptions: string | MongoLiteOptions)

Creates a new MongoLite client instance.

  • dbPathOrOptions: Either a string path to the SQLite database file (e.g., './mydb.sqlite', ':memory:') or an options object.
    • MongoLiteOptions:
      • filePath: string — Path to the SQLite database file.
      • verbose?: boolean — (Optional) Enable verbose logging from the sqlite3 driver.

async connect(): Promise<void>

Explicitly opens the database connection. Operations will automatically connect if the DB is not already open.

async close(): Promise<void>

Closes the database connection.

listCollections(): { toArray: () => Promise<string[]> }

Lists all collections (tables) in the database.

const collections = await client.listCollections().toArray();
console.log('Available collections:', collections);

collection<T>(name: string): MongoLiteCollection<T>

Gets a reference to a collection (table).

  • name: The name of the collection.
  • Returns a MongoLiteCollection instance.

syncToMongo(options: MongoSyncOptions): SyncReplicator

Replicates every insert, update and delete to an upstream MongoDB deployment. Requires the optional mongodb peer dependency.

  • options.connectionString: Upstream connection string (required).
  • options.collections / exclude / collectionMap: What to replicate, and under what names.
  • options.onConflict: What to do when a push loses a race. Defaults to the server winning.
  • options.versioning: Conditional writes against _v. Defaults to true.
  • Returns a SyncReplicator — call start() on it.
const sync = client.syncToMongo({ connectionString: process.env.MONGO_URL! });
await sync.start();
// …
await sync.stop({ flush: true });

See Syncing to MongoDB for the full option list, authentication, resilience behaviour and monitoring.

syncToHttp(options: HttpSyncOptions): SyncReplicator

Replicates to a remote HTTP API, which applies the changes to MongoDB on this client's behalf. For deployments that cannot reach the database directly.

  • options.baseUrl / options.database: Where to post (required).
  • options.getAuthHeaders: Resolved before every request, so short-lived tokens refresh.
  • options.fetch: Supply your own fetch (e.g. ofetch); defaults to the global one.

Mount createSyncReceiver from @semics-tech/mongolite/server on the API to receive the messages. See Syncing to MongoDB.

createSync(sink: SyncSink, options?: SyncOptions): SyncReplicator

The backend-agnostic form of the above. Pass any SyncSink implementation to replicate to something other than a MongoDB deployment — an HTTP API, a queue, or a test double.


MongoLiteCollection<T>

Represents a collection and provides methods to interact with its documents. T is a generic type for your document structure, which must extend DocumentWithId (i.e., have an optional _id: string field).

async insertOne(doc): Promise<InsertOneResult>

Inserts a single document. If _id is not provided, a UUID will be generated.

  • Returns { acknowledged: boolean; insertedId: string }.

async insertMany(docs): Promise<InsertManyResult>

Inserts multiple documents in a single operation.

  • Returns { acknowledged: boolean; insertedIds: string[] }.

async findOne(filter): Promise<T | null>

Finds a single document matching the filter. Returns null if not found.

find(filter): FindCursor<T>

Finds multiple documents matching the filter. Returns a chainable FindCursor.

async updateOne(filter, update): Promise<UpdateResult>

Updates a single document matching the filter.

  • Returns { acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }.

async updateMany(filter, update): Promise<UpdateResult>

Updates all documents matching the filter.

async deleteOne(filter): Promise<DeleteResult>

Deletes a single document matching the filter.

  • Returns { acknowledged: boolean; deletedCount: number }.

async deleteMany(filter): Promise<DeleteResult>

Deletes all documents matching the filter.

async replaceOne(filter, replacement): Promise<UpdateResult>

Replaces a single document matching the filter with the provided document.

async findOneAndUpdate(filter, update, options?): Promise<T | null>

Finds a document, updates it, and returns the original or updated document.

async findOneAndDelete(filter, options?): Promise<T | null>

Finds a document, deletes it, and returns the deleted document.

async findOneAndReplace(filter, replacement, options?): Promise<T | null>

Finds a document, replaces it, and returns the original or new document.

async distinct(field, filter?): Promise<unknown[]>

Returns an array of distinct values for the given field.

async countDocuments(filter?): Promise<number>

Returns the count of documents matching the filter.

async estimatedDocumentCount(): Promise<number>

Returns a fast estimate of the total document count.

async drop(): Promise<void>

Drops the collection (deletes the underlying table).

aggregate(pipeline): { toArray(): Promise<unknown[]> }

Runs an aggregation pipeline; call .toArray() to get the results. Supported stages: $match (including $expr), $project (including computed fields), $addFields/$set, $sort, $limit, $skip, $count, $group, $unwind (including preserveNullAndEmptyArrays and includeArrayIndex), $replaceRoot/$replaceWith, and $lookup (equality form from/localField/foreignField/as against another collection in the same database; the pipeline/let form is not supported). $group supports the accumulators $sum, $avg, $min, $max, $push, $addToSet, $first, $last and $count. Expressions support field paths and a common subset of operators ($add, $subtract, $multiply, $divide, $mod, $concat, $toUpper, $toLower, comparison and boolean operators, $cond, $ifNull, $size, $arrayElemAt, $first, $last, $literal). Unknown stages, accumulators or expression operators throw an error rather than being ignored. See COMPATIBILITY.md for the full table.

Each write is atomic on its own, and insertMany runs as a single SQLite transaction. For multi-document transactions, see client.startSession() below.

client.startSession(): ClientSession

Starts a session (also client.withSession(fn)). Use session.withTransaction(async () => { ... }) and pass { session } as the last option to collection calls (insertOne, insertMany, findOne, find, updateOne, updateMany, deleteOne, deleteMany, replaceOne, findOneAnd*, countDocuments, distinct, aggregate, …) that belong in the transaction. Commit on success, rollback on throw. Operations without the session wait until the transaction ends. Supported on better-sqlite3, node:sqlite and sql.js, and emulated with an undo log on the Cloudflare Durable Object adapter. Details and differences from MongoDB are in COMPATIBILITY.md.

session.withTransaction(fn, options?) retry (experimental)

await session.withTransaction(
  async () => {
    await orders.insertOne({ sku: 'a' }, { session });
  },
  { maxRetries: 3, retryDelayMs: 20 }
);
Option Default Meaning
maxRetries 0 Retries after a transient SQLITE_BUSY/SQLITE_LOCKED (0 to 10). 0 keeps the old single-attempt behaviour.
retryDelayMs 20 Base delay; doubles each attempt with jitter, capped at 500 ms.

readConcern, writeConcern and readPreference are still accepted and ignored.

When another connection or process holds the write lock for longer than busyTimeout, BEGIN IMMEDIATE (or a statement) fails with TransactionBusyError (code: 'SQLITE_BUSY', errorLabels: ['TransientTransactionError'], hasErrorLabel(label)), on node:sqlite, better-sqlite3 and sql.js. With maxRetries set, withTransaction rolls back, waits, and runs the callback again from scratch; after the limit it throws the last TransactionBusyError.

Warning: the callback may run more than once. It must be safe to re-run: no non-database side effects (emails, HTTP calls, counters) unless they are idempotent. Errors thrown by the callback itself, and commit errors other than busy, are never retried. startTransaction() is not retried; check err.hasErrorLabel('TransientTransactionError') and retry yourself. On Cloudflare Durable Objects transactions are emulated with an undo log; see COMPATIBILITY.md.

watch(options?): ChangeStream<T>

Opens a change stream to watch for changes on this collection.

See CHANGE_STREAMS.md for full documentation.


FindCursor<T>

Returned by collection.find(). Supports chaining before execution.

async toArray(): Promise<T[]>

Fetches all matching documents into an array.

async next(): Promise<T | null>

Returns the next document, or null when exhausted.

limit(count: number): FindCursor<T>

Limits the number of documents returned.

skip(count: number): FindCursor<T>

Skips the first N documents.

sort(sortCriteria): FindCursor<T>

Sorts results. Example: { age: -1, name: 1 } (1 = ascending, -1 = descending).

project(projection): FindCursor<T>

Specifies which fields to include or exclude in results.

async count(): Promise<number>

Returns the number of documents matching the cursor's filter (like MongoDB's cursor.count(), it ignores skip/limit but never the filter).


Indexing

async createIndex(fieldOrSpec, options?): Promise<CreateIndexResult>

Creates an index on the specified field(s).

  • fieldOrSpec: A field name string or an index spec object, e.g. { name: 1, age: -1 }.
  • options:
    • unique: Enforce uniqueness.
    • name: Custom index name.
    • sparse: Ignore documents without the indexed field.
  • Returns { acknowledged: boolean; name: string }.
// Simple index
await collection.createIndex({ name: 1 });

// Unique index
await collection.createIndex({ email: 1 }, { unique: true });

// Compound index
await collection.createIndex({ name: 1, age: -1 });

// Nested field index
await collection.createIndex({ 'address.city': 1 });

listIndexes(): { toArray: () => Promise<IndexInfo[]> }

Lists all indexes on the collection. Each IndexInfo contains name, key, and unique.

async dropIndex(indexName: string): Promise<DropIndexResult>

Drops the named index. Returns { acknowledged: boolean; name: string }.

async dropIndexes(): Promise<{ acknowledged: boolean; droppedCount: number }>

Drops all indexes except the one on _id.


Query Operators

Comparison

Operator Description
{ field: value } or { field: { $eq: value } } Equals
{ field: { $ne: value } } Not equals
{ field: { $gt: value } } Greater than
{ field: { $gte: value } } Greater than or equal
{ field: { $lt: value } } Less than
{ field: { $lte: value } } Less than or equal
{ field: { $in: [v1, v2] } } In array
{ field: { $nin: [v1, v2] } } Not in array
{ field: { $regex: pattern } } Matches regular expression
{ field: { $size: n } } Array has N elements
{ field: { $type: typeName } } Field is of given type
{ field: { $mod: [divisor, remainder] } } Modulo

Logical

Operator Description
{ $and: [f1, f2] } Logical AND
{ $or: [f1, f2] } Logical OR
{ $nor: [f1, f2] } Logical NOR
{ field: { $not: expr } } Negates a single operator expression

Element

Operator Description
{ field: { $exists: boolean } } Field exists (or not)

Array

Operator Description
{ field: { $all: [v1, v2] } } Array contains all values
{ field: { $elemMatch: query } } At least one element matches the query

Update Operators

Operator Description
$set Sets field values
$unset Removes fields
$inc Increments numeric fields
$mul Multiplies numeric fields
$min Sets field to minimum of current and given value
$max Sets field to maximum of current and given value
$push Appends a value to an array (supports $each)
$pull Removes matching values from an array
$addToSet Adds a value to an array only if it doesn't already exist
$pop Removes the first (-1) or last (1) element of an array
$currentDate Sets a field to the current date

Examples

// $set and $inc
await collection.updateOne({ _id: id }, { $set: { name: 'Bob' }, $inc: { age: 1 } });

// $push with $each
await collection.updateOne({ _id: id }, { $push: { scores: { $each: [90, 92, 85] } } });

// $pull
await collection.updateOne({ _id: id }, { $pull: { scores: 0 } });

// $addToSet
await collection.updateOne({ _id: id }, { $addToSet: { tags: 'new-tag' } });