### Install Minimongo Source: https://github.com/mwater/minimongo/blob/master/README.md Install the minimongo package using npm. ```bash npm install minimongo ``` -------------------------------- ### Contribute to Minimongo Source: https://github.com/mwater/minimongo/blob/master/README.md Clone the Minimongo repository, install dependencies, and run tests to contribute to the project. This setup is for development and testing purposes. ```bash git clone https://github.com/mWater/minimongo.git cd minimongo npm install npm test ``` -------------------------------- ### Example PATCH Request for Document Update Source: https://github.com/mwater/minimongo/blob/master/README.md This example demonstrates how to use the PATCH structure to change a document's field. Ensure the 'base' document accurately reflects the state before the patch. ```javascript { doc: { x:2, y: 1 }, base: { x:1, y: 1 } } ``` -------------------------------- ### GET / Source: https://context7.com/mwater/minimongo/llms.txt Retrieves documents from a collection based on query parameters. ```APIDOC ## GET / ### Description Retrieves documents from the specified collection. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **selector** (string) - Optional - JSON string representing the query filter - **fields** (string) - Optional - Fields to include or exclude - **sort** (string) - Optional - Sorting criteria - **limit** (number) - Optional - Maximum number of documents to return - **skip** (number) - Optional - Number of documents to skip ### Response #### Success Response (200) - **Array** (Array) - List of documents matching the query ``` -------------------------------- ### RemoteDb API Endpoints Source: https://github.com/mwater/minimongo/blob/master/README.md Details the API methods supported by RemoteDb for interacting with collections, including GET for queries and POST for find operations. ```APIDOC The API that RemoteDb should support four HTTP methods for each collection: #### GET `/` Performs a query, returning an array of results. GET query parameters are: - **selector** (optional): JSON of query, in MongoDB format. e.g., `{"a": 1}` to find records with field `a` having value `1` - **fields** (optional): JSON object indicating which fields to return in MongoDB format. e.g., `{"a": 1}` to return only field `a` and `_id` - **sort** (optional): JSON of MongoDB sort field. e.g., `["a"]` to sort ascending by `a`, or `[["a","desc"]]` to sort descending by `a` - **limit** (optional): Maximum records to return e.g., `100` Possible HTTP response codes: - **200**: normal response - **401**: client was invalid #### POST `//find` (optionally implemented) Performs a query, returning an array of results. POST body parameters are: - **selector** (optional): JSON of query, in MongoDB format. e.g., `{"a": 1}` to find records with field `a` having value `1` - **fields** (optional): JSON object indicating which fields to return in MongoDB format. e.g., `{"a": 1}` to return only field `a` and `_id` - **sort** (optional): JSON of MongoDB sort field. e.g., `["a"]` to sort ascending by `a`, or `[["a","desc"]]` to sort descending by `a` - **limit** (optional): Maximum records to return e.g., `100` Possible HTTP response codes: - **200**: normal response - **401**: client was invalid ``` -------------------------------- ### RemoteDb REST API Integration Source: https://context7.com/mwater/minimongo/llms.txt RemoteDb maps MongoDB-style operations to standard HTTP requests (GET, POST, PATCH, DELETE) for interacting with remote RESTful services. ```APIDOC ## [GET/POST/PATCH/DELETE] /collections/:collection ### Description RemoteDb translates database operations into HTTP requests. It supports standard CRUD operations and 3-way merges via PATCH. ### Methods - **find(selector, options)**: Performs a GET request to retrieve documents. - **upsert(doc, base)**: Performs a POST request for new documents or a PATCH request for updates (if base is provided). - **remove(id)**: Performs a DELETE request to remove a document. ### Request Example (Upsert) remoteDb.articles.upsert({ "_id": "article1", "title": "New Article" }); ### Response #### Success Response (200) - **document** (object) - The upserted or retrieved document. ``` -------------------------------- ### Initialize MemoryDb and Perform Operations Source: https://github.com/mwater/minimongo/blob/master/README.md Demonstrates setting up an in-memory database, adding a collection, and performing upsert and find operations. ```javascript // Require minimongo var minimongo = require("minimongo"); var LocalDb = minimongo.MemoryDb; // Create local db (in memory database with no backing) db = new LocalDb(); // Add a collection to the database db.addCollection("animals"); doc = { species: "dog", name: "Bingo" }; // Always use upsert for both inserts and modifies db.animals.upsert(doc, function() { // Success: // Query dog (with no query options beyond a selector) db.animals.findOne({ species:"dog" }, {}, function(res) { console.log("Dog's name is: " + res.name); }); }); // Access collections via collection for Typescript await db.collection["animals"].upsert(doc) ``` -------------------------------- ### Initialize IndexedDb and Perform Operations Source: https://github.com/mwater/minimongo/blob/master/README.md Demonstrates setting up a persistent database backed by IndexedDb and performing basic collection operations. ```javascript // Require minimongo var minimongo = require("minimongo"); var IndexedDb = minimongo.IndexedDb; // Create IndexedDb db = new IndexedDb({namespace: "mydb"}, function() { // Add a collection to the database db.addCollection("animals", function() { doc = { species: "dog", name: "Bingo" }; // Always use upsert for both inserts and modifies db.animals.upsert(doc, function() { // Success: // Query dog (with no query options beyond a selector) db.animals.findOne({ species:"dog" }, {}, function(res) { console.log("Dog's name is: " + res.name); }); }); }); }, function() { alert("some error!"); }); ``` -------------------------------- ### Initialize IndexedDb with Callbacks Source: https://context7.com/mwater/minimongo/llms.txt Set up persistent storage using IndexedDB with namespace. Includes adding a collection and upserting a document using callbacks. ```javascript import { IndexedDb } from 'minimongo'; // Create IndexedDb with namespace const db = new IndexedDb( { namespace: 'myapp' }, function() { // Success callback - database is ready console.log('Database initialized'); // Add collection db.addCollection('products', function() { // Collection ready // Upsert document db.products.upsert( { _id: 'prod1', name: 'Widget', price: 9.99, tags: ['sale', 'new'] }, function(doc) { console.log('Product saved:', doc); }, function(err) { console.error('Error:', err); } ); }); }, function(err) { // Error callback console.error('Failed to create IndexedDb:', err); } ); ``` -------------------------------- ### Initialize Hybrid Database Source: https://github.com/mwater/minimongo/blob/master/README.md Create a HybridDb instance to combine a local database with a remote source. Add collections to the hybrid database to enable querying and synchronization. ```javascript import { HybridDb } from 'minimongo'; const hybridDb = new HybridDb(localDb, remoteDb); hybridDb.addCollection('items'); ``` -------------------------------- ### Initialize and Use LocalStorageDb Source: https://context7.com/mwater/minimongo/llms.txt Create a synchronous, persistent database using browser localStorage. Includes adding a collection, upserting, and retrieving data. ```javascript import { LocalStorageDb } from 'minimongo'; // Create LocalStorageDb with namespace for persistence const db = new LocalStorageDb({ namespace: 'myapp' }, function(db) { console.log('LocalStorageDb ready'); }); db.addCollection('settings'); // Store user preferences await db.settings.upsert({ _id: 'user_prefs', theme: 'dark', language: 'en', notifications: true }); // Retrieve settings const prefs = await db.settings.findOne({ _id: 'user_prefs' }); console.log('Theme:', prefs.theme); // Data persists across page reloads // On page load, existing data is automatically restored ``` -------------------------------- ### Initialize Local Databases Source: https://github.com/mwater/minimongo/blob/master/README.md Instantiate MemoryDb or IndexedDb for local data storage. IndexedDb requires a namespace and callback functions for success and error. ```javascript import { MemoryDb, IndexedDb } from 'minimongo'; const memoryDb = new MemoryDb(); const indexedDb = new IndexedDb({namespace: 'mydb'}, successCallback, errorCallback); ``` -------------------------------- ### HybridDb Initialization and Usage Source: https://github.com/mwater/minimongo/blob/master/README.md Demonstrates how to initialize and use HybridDb to combine local and remote database results, including caching options and the upload mechanism. ```APIDOC ## HybridDb Combines results from the local database with remote data. Multiple options can be specified at the collection level and then overridden at the find/findOne level: **interim**: (default true) true to return interim results from the local database before the (slower) remote database has returned. If the remote database gives different results, the callback will be called a second time. This approach allows fast responses but with subsequent correction if the server has differing information. **cacheFind**: (default true) true to cache the `find` results from the remote database in the local database **cacheFindOne**: (default true) true to cache the `findOne` results from the remote database in the local database **shortcut**: (default false) true to return `findOne` results if any matching result is found in the local database. Useful for documents that change rarely. **useLocalOnRemoteError**: (default true) true to use local results if the remote find fails. Only applies if interim is false. To keep a local database and a remote database in sync, create a HybridDb: ```javascript hybridDb = new HybridDb(localDb, remoteDb) ``` Be sure to add the same collections to all three databases (local, hybrid, and remote). Then query the hybridDb (`find` and `findOne`) to have it get results and correctly combine them with any pending local results. If you are not interested in caching results, add `{ cacheFind: false, cacheFindOne: false }` to the options of `find` or `findOne` or to the `addCollection` options. When upserts and removes are done on the HybridDb, they are queued up in the LocalDb until `hybridDb.upload(success, error)` is called. `upload` will go through each collection and send any upserts or removes to the remoteDb. You must call this to have the results go to the server! Calling periodically (e.g., every 5 seconds) is safe as long as you wait for one upload call to complete before calling again. `findOne` will not return an interim `null` result, but will only return interim results when one is present. ``` -------------------------------- ### POST //quickfind Source: https://context7.com/mwater/minimongo/llms.txt Efficient synchronization endpoint for diff-based updates. ```APIDOC ## POST //quickfind ### Description An optional endpoint for efficient synchronization using encoded local data. ### Method POST ### Endpoint //quickfind ### Request Body - **selector** (Object) - Optional - Query filter - **sort** (Object) - Optional - Sort order - **limit** (number) - Optional - Result limit - **quickfind** (string) - Required - Encoded local data ### Response #### Success Response (200) - **Response** (string) - Encoded diff response ``` -------------------------------- ### Initialize IndexedDb with Async/Await Source: https://context7.com/mwater/minimongo/llms.txt Initialize IndexedDB and add a collection using Promises and async/await. Demonstrates upserting documents with and without base documents for conflict resolution. ```javascript async function initDatabase() { const db = await new Promise((resolve, reject) => { new IndexedDb({ namespace: 'myapp' }, resolve, reject); }); await new Promise((resolve, reject) => { db.addCollection('orders', resolve, reject); }); // Upsert with base document for conflict resolution const originalOrder = { _id: 'order1', status: 'pending', total: 100 }; await db.orders.upsert(originalOrder); // Later, update with base for 3-way merge support const updatedOrder = { _id: 'order1', status: 'shipped', total: 100 }; await db.orders.upsert(updatedOrder, originalOrder); return db; } ``` -------------------------------- ### Initialize HybridDb Source: https://github.com/mwater/minimongo/blob/master/README.md Create a HybridDb instance to synchronize local and remote databases. Ensure the same collections are added to all three databases (local, hybrid, and remote). ```javascript hybridDb = new HybridDb(localDb, remoteDb) ``` -------------------------------- ### Initialize Remote Database Source: https://github.com/mwater/minimongo/blob/master/README.md Set up a RemoteDb instance to connect to a remote data source. Specify the API endpoint, database name, and optional configuration like an HTTP client and quick find protocol. ```javascript import { RemoteDb } from 'minimongo'; const remoteDb = new RemoteDb('/api/collections', 'mydb', { httpClient: jQueryHttpClient, useQuickFind: true }); ``` -------------------------------- ### Initialize Replicating Database Source: https://github.com/mwater/minimongo/blob/master/README.md Instantiate a ReplicatingDb to synchronize operations between two database instances, ensuring data consistency across master and replica databases. ```javascript import { ReplicatingDb } from 'minimongo'; const replicatingDb = new ReplicatingDb(masterDb, replicaDb); ``` -------------------------------- ### Initialize and Use MemoryDb Source: https://context7.com/mwater/minimongo/llms.txt Create an in-memory database, add collections, and perform operations like upsert, find, and remove. Supports both callback and Promise-based APIs. ```javascript import { MemoryDb } from 'minimongo'; // Create database with clone safety (default) const db = new MemoryDb({ safety: 'clone' }); // Add a collection db.addCollection('users'); // Upsert a document (callback style) db.users.upsert({ _id: '1', name: 'John', age: 30 }, function(doc) { console.log('Upserted:', doc); }, function(err) { console.error('Error:', err); }); // Upsert with Promise const user = await db.users.upsert({ _id: '2', name: 'Jane', age: 25 }); // Upsert multiple documents await db.users.upsert([ { _id: '3', name: 'Bob', age: 35 }, { _id: '4', name: 'Alice', age: 28 } ]); // Find documents with selector db.users.find({ age: { $gte: 25 } }).fetch(function(results) { console.log('Found users:', results); // Output: [{ _id: '1', name: 'John', age: 30 }, ...] }); // Find with Promise const adults = await db.users.find({ age: { $gte: 18 } }).fetch(); // FindOne const john = await db.users.findOne({ name: 'John' }); // Remove document await db.users.remove('1'); // Remove by selector await db.users.remove({ age: { $lt: 30 } }); ``` -------------------------------- ### RemoteDb Initialization Source: https://github.com/mwater/minimongo/blob/master/README.md Explains how to initialize a RemoteDb instance to interact with a remote MongoDB database via AJAX-JSON calls. ```APIDOC ## RemoteDb Uses AJAX-JSON calls to an API to query a real Mongo database. API is simple and contains only query, upsert, patch, and remove commands. If the `client` field is passed to the constructor, it is appended as a query parameter (e.g., `?client=1234`) to each request made. Example code: ```javascript remoteDb = new minimongo.RemoteDb("http://someserver.com/api/", "myclientid123") ``` This would create a remote db that would make the following call to the API for a find to collection abc: `GET http://someserver.com/api/abc?client=myclientid123` The client is optional and is a string that is passed in each call only to make authentication easier. ``` -------------------------------- ### Auto-select Local Database with Minimongo Utilities Source: https://context7.com/mwater/minimongo/llms.txt Use `utils.autoselectLocalDb` to automatically select the best available local database (IndexedDB, WebSQL, LocalStorage, or MemoryDb). This function takes configuration options and provides a callback for the selected database or an error. ```javascript import { utils, MemoryDb, IndexedDb } from 'minimongo'; // Auto-select best available local database // Prefers: IndexedDb > WebSQL (iOS) > LocalStorage > Memory utils.autoselectLocalDb( { namespace: 'myapp' }, function(db) { console.log('Using:', db.constructor.name); // Continue with selected database }, function(err) { console.error('Database selection failed:', err); } ); ``` -------------------------------- ### Initialize and use HybridDb for offline-first synchronization Source: https://context7.com/mwater/minimongo/llms.txt Configures a hybrid database to cache remote data locally and handle offline updates. Use the interim flag to receive immediate local results followed by remote updates. ```javascript import { MemoryDb, RemoteDb, HybridDb } from 'minimongo'; // Create local and remote databases const localDb = new MemoryDb(); const remoteDb = new RemoteDb('https://api.example.com/', 'client123'); // Create hybrid database const hybridDb = new HybridDb(localDb, remoteDb); // Add collections to all databases localDb.addCollection('tasks'); remoteDb.addCollection('tasks'); hybridDb.addCollection('tasks', { cacheFind: true, // Cache find results locally cacheFindOne: true, // Cache findOne results locally interim: true, // Return local results while waiting for remote useLocalOnRemoteError: true, // Use local data if remote fails shortcut: false, // Return local result immediately if found timeout: 5000 // Remote timeout in ms }); // Query returns local data first, then updates with remote data hybridDb.tasks.find({ status: 'active' }).fetch( function(results) { // Called twice if interim=true: // 1. With local cached results (fast) // 2. With merged remote results (if different) console.log('Tasks:', results); }, function(err) { console.error('Query failed:', err); } ); // Upsert stores locally and queues for upload await hybridDb.tasks.upsert({ _id: 'task1', title: 'Complete project', status: 'active', priority: 'high' }); // Upload pending changes to remote server await hybridDb.upload(); // Check pending changes localDb.tasks.pendingUpserts(function(upserts) { console.log('Pending upserts:', upserts.length); }); localDb.tasks.pendingRemoves(function(removes) { console.log('Pending removes:', removes.length); }); ``` -------------------------------- ### Initialize RemoteDb Source: https://github.com/mwater/minimongo/blob/master/README.md Instantiate a RemoteDb to interact with a remote MongoDB database via AJAX. An optional client ID can be provided for authentication. ```javascript remoteDb = new minimongo.RemoteDb("http://someserver.com/api/", "myclientid123") ``` -------------------------------- ### Migrate and Clone Minimongo Databases Source: https://context7.com/mwater/minimongo/llms.txt Utilize `utils.migrateLocalDb` to transfer pending changes (upserts and removes) from one Minimongo database to another. `utils.cloneLocalDb` provides a way to create an exact copy of a database. ```javascript // Migrate pending changes between databases const oldDb = new MemoryDb(); const newDb = await new Promise((resolve, reject) => { new IndexedDb({ namespace: 'newdb' }, resolve, reject); }); // Add same collections to both oldDb.addCollection('items'); await new Promise((resolve, reject) => { newDb.addCollection('items', resolve, reject); }); // Migrate pending upserts and removes utils.migrateLocalDb( oldDb, newDb, function() { console.log('Migration complete'); }, function(err) { console.error('Migration failed:', err); } ); // Clone entire local database await utils.cloneLocalDb(oldDb, newDb); ``` -------------------------------- ### Perform MongoDB-style Queries Source: https://github.com/mwater/minimongo/blob/master/README.md Execute queries using MongoDB-like syntax, including regex, comparison operators, geospatial queries, sorting, and limiting. The .fetch() method retrieves the results. ```javascript collection.find({ name: { $regex: /^A/ }, age: { $gt: 18 }, location: { $near: { $geometry: { type: "Point", coordinates: [-73.9667, 40.78] }, $maxDistance: 1000 } } }, { sort: { age: -1 }, limit: 10 }).fetch(); ``` -------------------------------- ### Caching and Seeding Source: https://github.com/mwater/minimongo/blob/master/README.md Methods for managing local data synchronization and initial seeding. ```APIDOC ## Cache ### Description Caches a set of rows in the local database. ### Parameters - **docs** (array) - Required - Rows to cache. - **selector** (object) - Required - Selector used to perform the find. - **options** (object) - Required - Options used to perform the find. ## Seed ### Description Seeds rows into the local database. Does not overwrite existing rows; only ensures a row with the _id exists. ### Parameters - **docs** (array) - Required - Rows to seed. ``` -------------------------------- ### Synchronize databases with ReplicatingDb Source: https://context7.com/mwater/minimongo/llms.txt Use ReplicatingDb to keep a master and replica database in sync. Collections must be added to both underlying databases before being added to the replicating instance. ```javascript import { MemoryDb, IndexedDb, ReplicatingDb } from 'minimongo'; // Create master (fast in-memory) and replica (persistent) databases const masterDb = new MemoryDb(); const replicaDb = await new Promise((resolve, reject) => { new IndexedDb({ namespace: 'replica' }, resolve, reject); }); // Create replicating database const replicatingDb = new ReplicatingDb(masterDb, replicaDb); // Add collections to both underlying databases first masterDb.addCollection('documents'); await new Promise((resolve, reject) => { replicaDb.addCollection('documents', resolve, reject); }); // Add collection to replicating db replicatingDb.addCollection('documents'); // All operations are applied to both databases await replicatingDb.documents.upsert({ _id: 'doc1', title: 'My Document', content: 'Document content...' }); // Finds use master (faster) database const doc = await replicatingDb.documents.findOne({ _id: 'doc1' }); console.log('Found:', doc.title); // Remove also applies to both await replicatingDb.documents.remove('doc1'); ``` -------------------------------- ### Configure RemoteDb for RESTful API integration Source: https://context7.com/mwater/minimongo/llms.txt Connects to a remote API using standard HTTP methods. Supports custom HTTP clients and load balancing across multiple base URLs. ```javascript import { RemoteDb, jQueryHttpClient } from 'minimongo'; // Create remote database with custom HTTP client const remoteDb = new RemoteDb( 'https://api.example.com/collections/', // Base URL (must have trailing /) 'client_id_123', // Client identifier for auth jQueryHttpClient, // HTTP client (uses jQuery $.ajax) true, // useQuickFind - efficient sync protocol true // usePostFind - use POST for large queries ); remoteDb.addCollection('articles'); // Find documents - makes GET request // GET https://api.example.com/collections/articles?selector={"published":true}&limit=10 const articles = await remoteDb.articles.find( { published: true }, { limit: 10, sort: { date: -1 } } ).fetch(); // Upsert document - makes POST request // POST https://api.example.com/collections/articles const newArticle = await remoteDb.articles.upsert({ _id: 'article1', title: 'New Article', content: 'Article content...', published: true }); // Upsert with base document - makes PATCH request for 3-way merge // PATCH https://api.example.com/collections/articles const base = { _id: 'article1', title: 'Old Title', content: '...' }; const updated = { _id: 'article1', title: 'Updated Title', content: '...' }; await remoteDb.articles.upsert(updated, base); // Remove document - makes DELETE request // DELETE https://api.example.com/collections/articles/article1?client=client_id_123 await remoteDb.articles.remove('article1'); // Multiple URLs for load balancing const remoteDbMulti = new RemoteDb( ['https://api1.example.com/', 'https://api2.example.com/'], 'client_123' ); ``` -------------------------------- ### POST / Source: https://github.com/mwater/minimongo/blob/master/README.md Performs a single or batch upsert of documents into a collection. ```APIDOC ## POST / ### Description Performs a single upsert, returning the upserted row. If an array is provided, it upserts each document and returns an array of upserted documents. ### Method POST ### Endpoint / ### Parameters #### Path Parameters - **collection** (string) - Required - The name of the collection to upsert into. #### Request Body - **document** (object/array) - Required - The document or array of documents to upsert. ### Response #### Success Response (200) - **document** (object/array) - The upserted object(s). #### Error Responses - **400**: Document did not pass validation - **401**: Client was invalid or not present - **403**: Permission denied - **409**: Conflict; another client is upserting the same document - **410**: Document was already removed ``` -------------------------------- ### Manage Offline Data with Minimongo Caching Source: https://context7.com/mwater/minimongo/llms.txt Utilize caching mechanisms for offline data management. Use `cache` to store remote results with selector context, `seed` to add initial data without overwriting, and `cacheOne` for single documents. ```javascript import { MemoryDb, IndexedDb, HybridDb, RemoteDb } from 'minimongo'; const localDb = new MemoryDb(); const remoteDb = new RemoteDb('https://api.example.com/', 'client123'); const hybridDb = new HybridDb(localDb, remoteDb); localDb.addCollection('items'); remoteDb.addCollection('items'); hybridDb.addCollection('items'); // Cache remote results locally const remoteItems = [ { _id: '1', name: 'Item 1', _rev: 1 }, { _id: '2', name: 'Item 2', _rev: 1 } ]; // Cache documents with selector context localDb.items.cache( remoteItems, { category: 'active' }, // Selector used to fetch these items { sort: { name: 1 }, limit: 100 }, // Options used function() { console.log('Cached successfully'); }, function(err) { console.error('Cache error:', err); } ); // Seed data without overwriting existing documents localDb.items.seed( [{ _id: '3', name: 'Seeded Item' }], function() { console.log('Seeded'); }, function(err) { console.error('Seed error:', err); } ); // Cache single document localDb.items.cacheOne( { _id: '4', name: 'Single Item', _rev: 2 }, function() { console.log('Cached one'); }, function(err) { console.error('Error:', err); } ); // Uncache documents matching selector localDb.items.uncache( { category: 'archived' }, function() { console.log('Uncached archived items'); }, function(err) { console.error('Error:', err); } ); // Resolve pending upserts after successful server sync localDb.items.pendingUpserts(function(upserts) { // After server confirms the upserts... localDb.items.resolveUpserts( upserts, function() { console.log('Upserts resolved'); }, function(err) { console.error('Error:', err); } ); }, function(err) { console.error('Error:', err); }); // Resolve pending removes localDb.items.pendingRemoves(function(removeIds) { for (const id of removeIds) { localDb.items.resolveRemove( id, function() { console.log('Remove resolved:', id); }, function(err) { console.error('Error:', err); } ); } }, function(err) { console.error('Error:', err); }); ``` -------------------------------- ### RemoteDb Server API Endpoints and Client Implementation Source: https://context7.com/mwater/minimongo/llms.txt Defines the expected REST API structure for RemoteDb and provides a custom fetch-based HTTP client implementation. ```javascript // Server API endpoints expected by RemoteDb // GET / // Query parameters: selector, fields, sort, limit, skip // Response: Array of documents // Example: GET /items?selector={"active":true}&limit=10&sort=["name"] // POST / // Body: Document to upsert (or array of documents) // Response: Upserted document(s) // Used for new documents without base // PATCH / // Body: { doc: , base: } or arrays // Response: Merged document(s) // Used for updates with 3-way merge support // DELETE // // Response: 200 (success), 403 (forbidden), 410 (already deleted) // POST //find (optional, for large queries) // Body: { selector, fields, sort, limit, skip } // Response: Array of documents // POST //quickfind (optional, efficient sync) // Body: { selector, sort, limit, quickfind: } // Response: Encoded diff response // Custom HTTP client implementation const customHttpClient = function(method, url, params, data, success, error) { fetch(url + '?' + new URLSearchParams(params), { method: method, headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getToken() }, body: data ? JSON.stringify(data) : undefined }) .then(response => { if (!response.ok) { throw { status: response.status, message: response.statusText }; } return response.json(); }) .then(success) .catch(error); }; // Use custom HTTP client with RemoteDb const remoteDb = new RemoteDb( 'https://api.example.com/', 'client123', customHttpClient ); ``` -------------------------------- ### Generate Unique IDs with Minimongo Utilities Source: https://context7.com/mwater/minimongo/llms.txt Employ `utils.createUid` to generate a unique identifier string. This is useful for creating primary keys or other unique references within your application. ```javascript // Generate unique ID const id = utils.createUid(); console.log(id); // e.g., 'a1b2c3d4e5f64321abcdef' ``` -------------------------------- ### POST //find Source: https://context7.com/mwater/minimongo/llms.txt Performs complex queries for large datasets. ```APIDOC ## POST //find ### Description An optional endpoint for executing large queries using a request body. ### Method POST ### Endpoint //find ### Request Body - **selector** (Object) - Optional - Query filter - **fields** (Object) - Optional - Projection fields - **sort** (Object) - Optional - Sort order - **limit** (number) - Optional - Result limit - **skip** (number) - Optional - Skip count ### Response #### Success Response (200) - **Array** (Array) - List of documents ``` -------------------------------- ### Execute MongoDB-style queries Source: https://context7.com/mwater/minimongo/llms.txt Perform data retrieval using various MongoDB query operators including comparison, logical, and array-based selectors. Supports sorting, pagination, and field projection. ```javascript import { MemoryDb } from 'minimongo'; const db = new MemoryDb(); db.addCollection('products'); // Seed test data await db.products.upsert([ { _id: '1', name: 'Laptop', price: 999, category: 'electronics', tags: ['sale', 'new'], stock: 50 }, { _id: '2', name: 'Mouse', price: 29, category: 'electronics', tags: ['accessories'], stock: 200 }, { _id: '3', name: 'Desk', price: 299, category: 'furniture', tags: ['office'], stock: 0 }, { _id: '4', name: 'Chair', price: 199, category: 'furniture', tags: ['office', 'sale'], stock: 25 } ]); // Comparison operators: $lt, $lte, $gt, $gte, $ne const expensive = await db.products.find({ price: { $gte: 200 } }).fetch(); // Returns: Laptop, Desk // $in and $nin operators const electronics = await db.products.find({ category: { $in: ['electronics', 'accessories'] } }).fetch(); // $regex for pattern matching const startsWithL = await db.products.find({ name: { $regex: /^L/i } // Case-insensitive }).fetch(); // Logical operators: $and, $or, $nor, $not const onSaleAndInStock = await db.products.find({ $and: [ { tags: { $in: ['sale'] } }, { stock: { $gt: 0 } } ] }).fetch(); // Returns: Laptop, Chair const electronicsOrOnSale = await db.products.find({ $or: [ { category: 'electronics' }, { tags: 'sale' } ] }).fetch(); // $exists - check field presence const withDescription = await db.products.find({ description: { $exists: true } }).fetch(); // $elemMatch for array element matching const officeItems = await db.products.find({ tags: { $elemMatch: { $eq: 'office' } } }).fetch(); // $all - array contains all specified elements const saleAndNew = await db.products.find({ tags: { $all: ['sale', 'new'] } }).fetch(); // Returns: Laptop // Nested field queries await db.products.upsert({ _id: '5', name: 'Monitor', specs: { size: 27, resolution: '4K' } }); const largeMonitors = await db.products.find({ 'specs.size': { $gte: 24 } }).fetch(); // Sort, skip, and limit const paginated = await db.products.find( { category: 'electronics' }, { sort: { price: -1 }, skip: 0, limit: 10 } ).fetch(); // Field projection const namesOnly = await db.products.find( {}, { fields: { name: 1, price: 1 } } // Only return name, price, and _id ).fetch(); ``` -------------------------------- ### Perform Geospatial Queries with Minimongo Source: https://context7.com/mwater/minimongo/llms.txt Use $near for proximity searches and $geoIntersects for polygon intersection tests with GeoJSON data. Ensure data is added to a collection before querying. ```javascript import { MemoryDb } from 'minimongo'; const db = new MemoryDb(); db.addCollection('locations'); // Add GeoJSON Point locations await db.locations.upsert([ { _id: 'store1', name: 'Downtown Store', location: { type: 'Point', coordinates: [-73.9857, 40.7484] // [longitude, latitude] } }, { _id: 'store2', name: 'Uptown Store', location: { type: 'Point', coordinates: [-73.9654, 40.7829] } }, { _id: 'route1', name: 'Delivery Route', location: { type: 'LineString', coordinates: [ [-73.9857, 40.7484], [-73.9750, 40.7600], [-73.9654, 40.7829] ] } } ]); // $near - find locations near a point, sorted by distance const nearbyStores = await db.locations.find({ location: { $near: { $geometry: { type: 'Point', coordinates: [-73.9800, 40.7500] }, $maxDistance: 5000 // meters } } }).fetch(); // Results sorted by distance from query point // $geoIntersects - find locations within a polygon const inManhattan = await db.locations.find({ location: { $geoIntersects: { $geometry: { type: 'Polygon', coordinates: [[[-74.0, 40.7], [-73.9, 40.7], [-73.9, 40.8], [-74.0, 40.8], [-74.0, 40.7]]] } } } }).fetch(); ``` -------------------------------- ### Compile Document Selectors with Minimongo Utilities Source: https://context7.com/mwater/minimongo/llms.txt Use `utils.compileDocumentSelector` to transform a Minimongo query selector object into a JavaScript filter function. This function can then be used with `Array.prototype.filter` to efficiently query arrays of documents. ```javascript // Compile a selector to a filter function const filter = utils.compileDocumentSelector({ age: { $gte: 18 }, status: 'active' }); const users = [ { name: 'John', age: 25, status: 'active' }, { name: 'Jane', age: 16, status: 'active' }, { name: 'Bob', age: 30, status: 'inactive' } ]; const matches = users.filter(filter); console.log(matches); // [{ name: 'John', ... }] ``` -------------------------------- ### HybridDb Synchronization API Source: https://context7.com/mwater/minimongo/llms.txt The HybridDb class manages synchronization between a local MemoryDb and a remote database, allowing for offline-first data access and queued updates. ```APIDOC ## HybridDb Synchronization ### Description HybridDb provides a wrapper around local and remote databases to enable offline-first functionality. It supports caching, interim result callbacks, and automatic synchronization of pending changes. ### Methods - **upsert(doc)**: Stores a document locally and queues it for remote upload. - **upload()**: Synchronizes pending local changes to the remote server. - **find(selector)**: Queries the database, returning local data immediately if configured. ### Request Example await hybridDb.tasks.upsert({ "_id": "task1", "title": "Complete project", "status": "active" }); ``` -------------------------------- ### Register and Use Custom EJSON Types Source: https://context7.com/mwater/minimongo/llms.txt Extend EJSON with custom data types by defining a class with specific methods like `typeName`, `toJSONValue`, `clone`, and `equals`. Register the type using `EJSON.addType` for serialization and deserialization. ```javascript // Add custom type class Money { constructor(amount, currency) { this.amount = amount; this.currency = currency; } typeName() { return 'Money'; } toJSONValue() { return { amount: this.amount, currency: this.currency }; } clone() { return new Money(this.amount, this.currency); } equals(other) { return other instanceof Money && this.amount === other.amount && this.currency === other.currency; } } EJSON.addType('Money', function(value) { return new Money(value.amount, value.currency); }); ``` -------------------------------- ### Resolve Pending Removals Source: https://github.com/mwater/minimongo/blob/master/README.md Retrieves pending removals from a collection and resolves them individually. ```javascript const idsToRemove = await new Promise((resolve, reject) => collection.pendingRemoves(resolve, reject)) for (const id of idsToRemove) { await new Promise((resolve, reject) => collection.resolveRemove(id, resolve, reject)) } ``` -------------------------------- ### Handle Data Conflicts with Upsert Source: https://github.com/mwater/minimongo/blob/master/README.md Resolve data conflicts during upsert operations by providing the base document version. This ensures that updates are applied correctly based on the document's previous state. ```javascript collection.upsert( { _id: '1', name: 'updated' }, { _id: '1', name: 'original' }, // base document successCallback ); ``` -------------------------------- ### PATCH Request Structure for Document Update Source: https://github.com/mwater/minimongo/blob/master/README.md Use this structure when performing a PATCH operation to update a document. The 'doc' field contains the new document state, and 'base' provides the original document for comparison. ```javascript { doc: , base: } ``` -------------------------------- ### EJSON Deep Equality and Cloning Source: https://context7.com/mwater/minimongo/llms.txt Perform deep equality checks and deep cloning of objects using EJSON. Cloning ensures that nested objects and arrays are copied by value, preventing unintended modifications to the original object. ```javascript // Deep equality comparison const a = { date: new Date('2024-01-01'), arr: [1, 2, 3] }; const b = { date: new Date('2024-01-01'), arr: [1, 2, 3] }; console.log(EJSON.equals(a, b)); // true ``` ```javascript // Deep clone const original = { nested: { value: [1, 2, 3] } }; const cloned = EJSON.clone(original); cloned.nested.value.push(4); console.log(original.nested.value); // [1, 2, 3] - unchanged ``` -------------------------------- ### Collection Operations Source: https://github.com/mwater/minimongo/blob/master/README.md Methods for managing data within a collection, including upserting, removing, and finding documents. ```APIDOC ## Upsert ### Description Inserts or modifies documents in a collection. Supports both single documents and arrays. ### Method POST/PUT (Internal Method) ### Parameters - **docs** (object|array) - Required - The document(s) to upsert. - **bases** (object|array) - Optional - The base version for the update. If omitted, uses current cached value. If null, forces an overwrite. ## Remove ### Description Removes a document from the collection by its ID. ### Parameters - **docId** (string) - Required - The ID of the document to remove. ## Find ### Description Queries the collection using a MongoDB-style selector and options. ### Parameters - **selector** (object) - Required - MongoDB selector (e.g., { x: 5 }). - **options** (object) - Optional - MongoDB find options (e.g., { limit: 10 }). ``` -------------------------------- ### PATCH / Source: https://github.com/mwater/minimongo/blob/master/README.md Performs a patch operation on a document to support three-way merging. ```APIDOC ## PATCH / ### Description Performs a patch, returning the upserted row. Uses a base document to facilitate three-way merging. ### Method PATCH ### Endpoint / ### Request Body - **doc** (object/array) - Required - The document in its new form. - **base** (object/array) - Required - The base document on which changes were made. ### Response #### Success Response (200) - **document** (object) - The upserted object. #### Error Responses - **400**: Document did not pass validation - **401**: Client was invalid or not present - **403**: Permission denied - **409**: Conflict; another client is upserting the same document - **410**: Document was already removed ``` -------------------------------- ### Serialize and Deserialize Extended JSON with EJSON Source: https://context7.com/mwater/minimongo/llms.txt Use EJSON to convert JavaScript objects with extended types (Date, Uint8Array) to a JSON-compatible format and back. This preserves type information during serialization and deserialization. ```javascript import { EJSON } from 'minimongo'; // Serialize Date objects const doc = { _id: '1', createdAt: new Date(), data: new Uint8Array([1, 2, 3, 4]) }; // Convert to JSON-compatible format const jsonValue = EJSON.toJSONValue(doc); console.log(jsonValue); // { _id: '1', createdAt: { $date: 1234567890 }, data: { $binary: 'AQIDBA==' } } // Convert back from JSON format const restored = EJSON.fromJSONValue(jsonValue); console.log(restored.createdAt instanceof Date); // true ``` ```javascript // Stringify and parse (like JSON but with type preservation) const str = EJSON.stringify(doc); const parsed = EJSON.parse(str); ``` -------------------------------- ### DELETE // Source: https://context7.com/mwater/minimongo/llms.txt Deletes a specific document by ID. ```APIDOC ## DELETE // ### Description Removes a document from the collection. ### Method DELETE ### Endpoint // ### Response #### Success Response (200) - **Status** (number) - 200 for success, 403 for forbidden, 410 if already deleted ``` -------------------------------- ### DELETE //<_id> Source: https://github.com/mwater/minimongo/blob/master/README.md Removes a single document from a collection by its ID. ```APIDOC ## DELETE //<_id> ### Description Removes a document by its unique identifier. ### Method DELETE ### Endpoint //<_id> ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name. - **_id** (string) - Required - The ID of the document to remove. ### Response #### Success Response (200) - **status** (string) - Document was removed. #### Error Responses - **401**: Client was invalid or not present - **403**: Permission denied - **410**: Document was already removed ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.