### Complete Async/Await Example Source: https://github.com/apache/couchdb-nano/blob/main/README.md A comprehensive example demonstrating database destruction, creation, and document insertion using async/await. ```javascript async function asyncCall() { await nano.db.destroy('alice') await nano.db.create('alice') const alice = nano.use('alice') const response = await alice.insert({ happy: true }, 'rabbit') return response } asyncCall() ``` -------------------------------- ### Get Document with Query Parameters Source: https://github.com/apache/couchdb-nano/blob/main/README.md Fetch a document with optional query string parameters using `alice.get('docId', params)`. For example, `revs_info: true` can be used to get revision information. ```js const doc = await alice.get('rabbit', { revs_info: true }) ``` -------------------------------- ### Running Nano Tests Source: https://github.com/apache/couchdb-nano/blob/main/README.md Instructions for setting up and running the test suite for the Nano library. This involves navigating to the nano directory, installing dependencies, and executing the test command. ```sh cd nano npm install npm run test ``` -------------------------------- ### List All CouchDB Databases with Nano Source: https://context7.com/apache/couchdb-nano/llms.txt Get a list of all database names on the CouchDB server using `nano.db.list`. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const databases = await nano.db.list(); console.log(databases); // Output: ['_replicator', '_users', 'mydb', 'customers', 'orders'] ``` -------------------------------- ### GET /db/list Source: https://context7.com/apache/couchdb-nano/llms.txt Returns an array of all database names on the CouchDB server. ```APIDOC ## GET /db/list Returns an array of all database names on the CouchDB server. ### Method GET ### Endpoint `/db/list` ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const databases = await nano.db.list(); console.log(databases); ``` ### Response #### Success Response (200) - **databases** (array) - An array of database names. #### Response Example ```json [ "_replicator", "_users", "mydb", "customers", "orders" ] ``` ``` -------------------------------- ### Get Partition Statistics with db.partitionInfo Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves statistics for a specific partition in a partitioned database. Requires the partition key as an argument. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const db = nano.use('partitioned-db'); const stats = await db.partitionInfo('canidae'); console.log(stats); ``` -------------------------------- ### Get General Database Information Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieves general information about the current database context. This is an alias for `nano.db.get` when no specific database name is provided. ```javascript const info = await nano.db.info() ``` -------------------------------- ### Stream CouchDB Database Names with Nano Source: https://context7.com/apache/couchdb-nano/llms.txt Use `nano.db.listAsStream` to get a stream of all database names. This is efficient for servers with many databases, preventing memory overload. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); nano.db.listAsStream() .on('error', (e) => console.error('error', e)) .pipe(process.stdout); ``` -------------------------------- ### Start Listening to Changes Feed Indefinitely Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `changesReader.start()` to continuously poll for changes until `changesReader.stop()` is called. Monitor 'change', 'batch', 'seq', or 'error' events. ```javascript const db = nano.db.use('mydb') db.changesReader.start() .on('change', (change) => { console.log(change) }) .on('batch', (b) => { console.log('a batch of', b.length, 'changes has arrived'); }).on('seq', (s) => { console.log('sequence token', s); }).on('error', (e) => { console.error('error', e); }) ``` -------------------------------- ### Initialization and Configuration Source: https://context7.com/apache/couchdb-nano/llms.txt Connect to a CouchDB server by passing the URL to the nano constructor. Configuration can include custom headers, agent options, and logging functions. You can also connect directly to a specific database or use custom agent options for connection pooling. ```APIDOC ## Initialization and Configuration Connect to a CouchDB server by passing the URL to the nano constructor. You can specify just the URL string or provide a configuration object with custom headers, agent options, and logging functions. ```javascript // Simple connection const nano = require('nano')('http://127.0.0.1:5984'); // With configuration object const nano = require('nano')({ url: 'http://127.0.0.1:5984', headers: { 'mycustomheader': '42' }, log: console.log // Optional: log all requests/responses }); // Connect directly to a specific database const db = require('nano')('http://127.0.0.1:5984/mydb'); // Custom agent options for connection pooling const undici = require('undici'); const agentOptions = { bodyTimeout: 30000, headersTimeout: 30000, keepAliveMaxTimeout: 600000, keepAliveTimeout: 30000, pipelining: 6, connect: { timeout: 10000 } }; const nano = require('nano')({ url: 'http://127.0.0.1:5984', agentOptions: new undici.Agent(agentOptions) }); ``` ``` -------------------------------- ### Get Document Headers Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieve only the headers for a document using `alice.head('docId')`. This is a lightweight alternative to `get` when only metadata is needed. ```js const headers = await alice.head('rabbit') ``` -------------------------------- ### Get Document Headers Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves only the HTTP headers for a document. Useful for checking existence or getting the current revision (ETag) without downloading the document body. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const db = nano.use('mydb'); const headers = await db.head('mydoc'); console.log(headers); // Extract revision from etag const rev = headers.etag.replace(/ ``` -------------------------------- ### Create a Partitioned Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Create a partitioned database by passing `{ partitioned: true }` to `db.create`. This enables features specific to partitioned databases. ```javascript await nano.db.create('my-partitioned-db', { partitioned: true }) ``` -------------------------------- ### Basic Logging Configuration Source: https://github.com/apache/couchdb-nano/blob/main/README.md Configure Nano to use `console.log` for logging all requests and responses during instantiation. This provides a simple way to monitor library activity. ```javascript const nano = Nano({ url: process.env.COUCH_URL, log: console.log }) // all requests and responses will be sent to console.log ``` -------------------------------- ### Attachment Get API Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieves a specific attachment from a document. ```APIDOC ## GET /db/{docname}/{attname} ### Description Retrieves a specific attachment from a document. Optional query string parameters can be provided. ### Method GET ### Endpoint /db/{docname}/{attname} ### Parameters #### Path Parameters - **docname** (string) - Required - The name of the document. - **attname** (string) - Required - The name of the attachment. #### Query Parameters - **params** (object) - Optional - Query string parameters. ### Response #### Success Response (200) - **body** (Buffer) - The content of the attachment. ``` -------------------------------- ### Connect to CouchDB with Nano Source: https://context7.com/apache/couchdb-nano/llms.txt Initialize the Nano client by providing the CouchDB URL. You can pass a simple URL string or a configuration object with custom headers, agent options, and logging. It's also possible to connect directly to a specific database. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); ``` ```javascript const nano = require('nano')({ url: 'http://127.0.0.1:5984', headers: { 'mycustomheader': '42' }, log: console.log // Optional: log all requests/responses }); ``` ```javascript const db = require('nano')('http://127.0.0.1:5984/mydb'); ``` ```javascript const undici = require('undici'); const agentOptions = { bodyTimeout: 30000, headersTimeout: 30000, keepAliveMaxTimeout: 600000, keepAliveTimeout: 30000, pipelining: 6, connect: { timeout: 10000 } }; const nano = require('nano')({ url: 'http://127.0.0.1:5984', agentOptions: new undici.Agent(agentOptions) }); ``` -------------------------------- ### Attachment Get API Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves an attachment from a document as a Buffer. ```APIDOC ## GET /db/{docname}/{attname} ### Description Retrieves an attachment from a document as a Buffer. ### Method GET ### Endpoint /db/{docname}/{attname} ### Parameters #### Path Parameters - **docname** (string) - Required - The name of the document. - **attname** (string) - Required - The name of the attachment. #### Query Parameters - **rev** (string) - Optional - The revision of the document to retrieve the attachment from. ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const fs = require('fs'); const db = nano.use('mydb'); const attachment = await db.attachment.get('mydoc', 'photo.png'); fs.writeFileSync('downloaded-photo.png', attachment); ``` ### Response #### Success Response (200) - **attachment** (Buffer) - The content of the attachment. ``` -------------------------------- ### Create a New Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use the nano.db.create method to initialize a new database in CouchDB. ```javascript nano.db.create('alice'); ``` -------------------------------- ### Use a Partitioned Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Access a partitioned database using `nano.db.use`. Documents in partitioned databases require a two-part `_id` formatted as `:`. ```javascript const db = nano.db.use('my-partitioned-db') ``` -------------------------------- ### Attachment Get Stream API Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieves a specific attachment from a document as a stream. ```APIDOC ## GET /db/{docname}/{attname} ### Description Retrieves a specific attachment from a document as a readable stream. Optional query string parameters can be provided. ### Method GET ### Endpoint /db/{docname}/{attname} ### Parameters #### Path Parameters - **docname** (string) - Required - The name of the document. - **attname** (string) - Required - The name of the attachment. #### Query Parameters - **params** (object) - Optional - Query string parameters. ### Response #### Success Response (200) - **stream** - A readable stream of the attachment content. ``` -------------------------------- ### Connect to CouchDB Source: https://github.com/apache/couchdb-nano/blob/main/README.md Initialize the Nano library to connect to your CouchDB instance. Authentication credentials in the URL are deprecated; use nano.auth instead. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); ``` -------------------------------- ### Multipart Get API Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves a document along with all its attachments in a single multipart HTTP response. ```APIDOC ## GET /db/{docname} ### Description Retrieves a document along with all its attachments in a single multipart HTTP response. ### Method GET ### Endpoint /db/{docname} ### Parameters #### Path Parameters - **docname** (string) - Required - The name of the document. #### Query Parameters - **attachments** (boolean) - Optional - Set to true to include attachments. Defaults to true when using multipart. - **att_encoding_info** (boolean) - Optional - Include attachment encoding information. - **full** (boolean) - Optional - Include full attachment details. ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const db = nano.use('mydb'); const response = await db.multipart.get('project-files'); // Response is a multipart buffer containing document and attachments ``` ### Response #### Success Response (200) - **response** (Buffer) - A multipart buffer containing the document and its attachments. ``` -------------------------------- ### Configure Nano with URL and Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Configure Nano to connect to a specific database by including the database name in the connection URL. ```javascript const nano = require('nano')('http://127.0.0.1:5984') const db = nano.use('foo'); ``` -------------------------------- ### Attachment Get as Stream API Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves an attachment as a Node.js stream, useful for large files. ```APIDOC ## GET /db/{docname}/{attname} ### Description Retrieves an attachment as a Node.js stream, useful for large files. ### Method GET ### Endpoint /db/{docname}/{attname} ### Parameters #### Path Parameters - **docname** (string) - Required - The name of the document. - **attname** (string) - Required - The name of the attachment. #### Query Parameters - **rev** (string) - Optional - The revision of the document to retrieve the attachment from. ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const fs = require('fs'); const db = nano.use('mydb'); db.attachment.getAsStream('mydoc', 'large-video.mp4') .on('error', (e) => console.error('error', e)) .pipe(fs.createWriteStream('video.mp4')); ``` ### Response #### Success Response (200) - **stream** (ReadableStream) - A Node.js readable stream of the attachment content. ``` -------------------------------- ### Get Document Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieve a document from CouchDB by its ID using `alice.get('docId')`. This fetches the entire document. ```js const doc = await alice.get('rabbit') ``` -------------------------------- ### Create Mango Index for Partitioned Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Create Mango indexes that operate on a per-partition basis by supplying `partitioned: true` during index creation. This allows for efficient querying within specific partitions. ```javascript const i = { ddoc: 'partitioned-query', index: { fields: ['name'] }, name: 'name-index', partitioned: true, type: 'json' } // instruct CouchDB to create the index await db.index(i) ``` -------------------------------- ### Enable Continuous Replication Source: https://context7.com/apache/couchdb-nano/llms.txt Sets up a continuous replication that persists across server restarts by creating a document in the `_replicator` database. The `continuous` option must be set to `true`. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const response = await nano.db.replication.enable( 'source-db', 'http://admin:password@otherhost.com:5984/target-db', { create_target: true, continuous: true } ); console.log('Replication ID:', response.id); ``` -------------------------------- ### Get CouchDB Database Information Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieves information about a specific CouchDB database. The database must exist. ```javascript const info = await nano.db.get('alice') ``` -------------------------------- ### Use an Existing Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Access an existing database using nano.db.use to perform operations on it. ```javascript const alice = nano.db.use('alice'); ``` -------------------------------- ### Stream Search Results Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.searchAsStream` to get search results as a stream. This is efficient for large result sets. ```javascript alice.search('characters', 'happy_ones', { q: 'cat' }).pipe(process.stdout); ``` -------------------------------- ### Create a CouchDB Database with Nano Source: https://context7.com/apache/couchdb-nano/llms.txt Use `nano.db.create` to create a new database. You can specify options like the number of replicas (`n`), whether the database should be partitioned, and the number of shards (`q`). ```javascript const nano = require('nano')('http://127.0.0.1:5984'); // Create a simple database await nano.db.create('mydb'); ``` ```javascript await nano.db.create('mydb', { n: 3 }); ``` ```javascript await nano.db.create('partitioned-db', { partitioned: true }); // Output: { ok: true } ``` -------------------------------- ### Get Database Changes Feed Source: https://github.com/apache/couchdb-nano/blob/main/README.md Fetches the changes feed for a specified database. Additional query parameters can be provided. ```javascript const c = await nano.db.changes('alice') ``` -------------------------------- ### Create Search Index for Partitioned Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Create search indexes for partitioned databases by defining a design document with `options.partitioned = true`. This allows for full-text search capabilities within partitions. ```javascript // the search definition const func = function(doc) { index('name', doc.name) index('latin', doc.latin) } // the design document containing the search definition function const ddoc = { _id: '_design/search-ddoc', indexes: { search-index: { index: func.toString() } }, options: { partitioned: true } } await db.insert(ddoc) ``` -------------------------------- ### Configuration Source: https://github.com/apache/couchdb-nano/blob/main/README.md Accesses the configuration object for the Nano instance. ```APIDOC ## nano.config ### Description An object containing the `nano` configurations. Possible keys are `url` and `db`. ### Properties - **url** (string) - The CouchDB URL. - **db** (string) - The database name. ### Example ```javascript console.log(nano.config.url); console.log(nano.config.db); ``` ``` -------------------------------- ### Get Current Session Info Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves information about the currently authenticated user session. Requires prior authentication. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); await nano.auth('admin', 'mypassword'); const session = await nano.session(); console.log(session); ``` -------------------------------- ### Get Server Information Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves general information about the CouchDB server, including its version, UUID, and supported features. ```APIDOC ## GET /info ### Description Retrieves meta information about the CouchDB server, including version and enabled features. ### Method GET ### Endpoint `/info` ### Parameters None ### Request Example ```javascript const info = await nano.info(); ``` ### Response #### Success Response (200) - **couchdb** (string) - A welcome message from CouchDB. - **version** (string) - The version of the CouchDB server. - **git_sha** (string) - The Git commit SHA of the CouchDB build. - **uuid** (string) - A unique identifier for the CouchDB server. - **features** (array) - A list of enabled features. - **vendor** (object) - Information about the CouchDB vendor. - **name** (string) - The name of the vendor. #### Response Example ```json { "couchdb": "Welcome", "version": "3.3.2", "git_sha": "abc123", "uuid": "unique-server-id", "features": ["access-ready", "partitioned", "pluggable-storage-engines"], "vendor": { "name": "The Apache Software Foundation" } } ``` ``` -------------------------------- ### POST /db/create Source: https://context7.com/apache/couchdb-nano/llms.txt Creates a new CouchDB database with the specified name. Optional parameters include the number of replicas (`n`), whether the database should be partitioned, and the number of shards (`q`). ```APIDOC ## POST /db/create Creates a new CouchDB database with the specified name. Optional parameters include the number of replicas (`n`), whether the database should be partitioned, and the number of shards (`q`). ### Method POST ### Endpoint `/db/create` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the database to create. - **opts** (object) - Optional - Options for database creation. - **n** (number) - The number of replicas. - **partitioned** (boolean) - Whether the database should be partitioned. - **q** (number) - The number of shards. ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); // Create a simple database await nano.db.create('mydb'); // Create with options await nano.db.create('mydb', { n: 3 }); // Create a partitioned database await nano.db.create('partitioned-db', { partitioned: true }); ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### List Documents with Query Parameters Source: https://github.com/apache/couchdb-nano/blob/main/README.md List documents with optional query string parameters using `alice.list(params)`. `include_docs: true` can be passed to include full document bodies. ```js const doclist = await alice.list({include_docs: true}) ``` -------------------------------- ### Get attachment as a stream from a document Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.attachment.getAsStream` to retrieve an attachment from a document as a readable stream. This is efficient for large attachments. ```javascript const fs = require('fs'); alice.attachment.getAsStream('rabbit', 'rabbit.png') .on('error', e => console.error) .pipe(fs.createWriteStream('rabbit.png')); ``` -------------------------------- ### Get attachment from a document Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.attachment.get` to retrieve a specific attachment from a document. Optional query string parameters can be provided. ```javascript const fs = require('fs'); const body = await alice.attachment.get('rabbit', 'rabbit.png') fs.writeFile('rabbit.png', body) ``` -------------------------------- ### Execute Mango Query on a Partition with db.partitionedFind Source: https://context7.com/apache/couchdb-nano/llms.txt Executes a Mango query scoped to a specific partition for improved performance. Requires the partition key and a query object. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const db = nano.use('partitioned-db'); const result = await db.partitionedFind('canidae', { selector: { species: 'wolf' }, fields: ['_id', 'name', 'habitat'] }); console.log(result); ``` -------------------------------- ### GET /db/listAsStream Source: https://context7.com/apache/couchdb-nano/llms.txt Returns a stream of all database names, useful for servers with many databases to avoid loading all names into memory. ```APIDOC ## GET /db/listAsStream Returns a stream of all database names, useful for servers with many databases to avoid loading all names into memory. ### Method GET ### Endpoint `/db/listAsStream` ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); nano.db.listAsStream() .on('error', (e) => console.error('error', e)) .pipe(process.stdout); ``` ``` -------------------------------- ### Create MapReduce View for Partitioned Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Create MapReduce views for partitioned databases by defining a design document with `options.partitioned = true`. This enables aggregation and transformation of data within partitions. ```javascript const func = function(doc) { emit(doc.family, doc.weight) } // Design Document const ddoc = { _id: '_design/view-ddoc', views: { family-weight: { map: func.toString(), reduce: '_sum' } }, options: { partitioned: true } } // create design document await db.insert(ddoc) ``` -------------------------------- ### GET /db/get Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves metadata about a specific database, including document count, disk size, and update sequence number. ```APIDOC ## GET /db/get Retrieves metadata about a specific database, including document count, disk size, and update sequence number. ### Method GET ### Endpoint `/db/get` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the database to retrieve metadata for. ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const info = await nano.db.get('mydb'); console.log(info); ``` ### Response #### Success Response (200) - **db_name** (string) - The name of the database. - **doc_count** (number) - The number of documents in the database. - **doc_del_count** (number) - The number of deleted documents. - **update_seq** (string) - The update sequence number. - **disk_size** (number) - The disk size of the database. - **sizes** (object) - An object containing size information. - **active** (number) - The active size. - **external** (number) - The external size. - **file** (number) - The file size. - **compact_running** (boolean) - Indicates if compaction is running. #### Response Example ```json { "db_name": "mydb", "doc_count": 42, "doc_del_count": 3, "update_seq": "45-g1AAAABXeJzL...", "disk_size": 12345, "sizes": { "active": 1234, "external": 2345, "file": 12345 }, "compact_running": false } ``` ``` -------------------------------- ### Initiate One-Time Replication Source: https://context7.com/apache/couchdb-nano/llms.txt Use to perform a single replication from a source to a target database. The target can be local or remote. The `create_target` option can be used to create the target database if it does not exist. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); // Replicate between local databases const response = await nano.db.replicate('source-db', 'target-db'); ``` ```javascript const response = await nano.db.replicate( 'alice', 'http://admin:password@otherhost.com:5984/alice', { create_target: true } ); ``` -------------------------------- ### Get User Session Information Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieve the current user's session information, including their roles and username, after successful authentication. ```javascript const doc = await nano.session() // { userCtx: { roles: [ '_admin', '_reader', '_writer' ], name: 'rita' }, ok: true } ``` -------------------------------- ### Configure Agent Options with Undici Source: https://github.com/apache/couchdb-nano/blob/main/migration_guide_v10_to_v11.md When supplying non-default connection handling parameters in Nano 11, use `agentOptions` instead of `requestDefaults`. This requires the `undici` module to be a project dependency. ```javascript const agentOptions = { bodyTimeout: 30000, headersTimeout: 30000, keepAliveMaxTimeout: 600000, keepAliveTimeout: 30000, keepAliveTimeoutThreshold: 1000, maxHeaderSize: 16384, maxResponseSize: -1, pipelining: 6, connect: { timeout: 10000 }, strictContentLength: true, connections: null, maxRedirections: 0 } const undici = require('undici') const undiciOptions = new undici.Agent(agentOptions) const nano = Nano({ url: 'http://127.0.0.1:5984', undiciOptions }) ``` -------------------------------- ### Get Database Changes as Stream Source: https://context7.com/apache/couchdb-nano/llms.txt Provides the changes feed for a database as a Node.js stream, which is efficient for processing large numbers of changes. ```APIDOC ## GET /db/changesAsStream ### Description Returns the changes feed as a Node.js stream for processing large change sets efficiently. ### Method GET ### Endpoint `/db/changesAsStream` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the database to get changes from. #### Query Parameters - **params** (object) - Optional - Parameters for filtering or modifying the changes feed. - **since** (string) - Optional - The sequence number to start retrieving changes from. - **include_docs** (boolean) - Optional - If true, includes the full document for each change. ### Request Example ```javascript nano.db.changesAsStream('mydb', { since: '0', include_docs: true }) .on('error', (e) => console.error('error', e)) .pipe(process.stdout); ``` ### Response This endpoint returns a readable stream. Each chunk emitted by the stream represents a change in the database. Error events are emitted on the stream for any issues during the process. ``` -------------------------------- ### List Documents using Async/Await Source: https://github.com/apache/couchdb-nano/blob/main/migration_guide_v10_to_v11.md The `await` pattern is the recommended way to handle asynchronous operations in Nano 11, replacing the older callback style. ```javascript const data = await db.list() console.log('response', data) ``` -------------------------------- ### Get document with attachments using multipart Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.multipart.get` to retrieve a document and its attachments via a multipart/related request. The response body is a Buffer. ```javascript const response = await alice.multipart.get('rabbit') ``` -------------------------------- ### List Documents from a Partition Source: https://github.com/apache/couchdb-nano/blob/main/README.md Fetch documents from a database partition using `db.partitionedList(partitionKey, [params])`. You can include document bodies and limit the response size. ```javascript // fetch document id/revs from a partition const docs = await alice.partitionedList('canidae') // add document bodies but limit size of response const docs = await alice.partitionedList('canidae', { include_docs: true, limit: 5 }) ``` -------------------------------- ### Enable Continuous Replication Source: https://context7.com/apache/couchdb-nano/llms.txt Sets up a continuous replication that will automatically restart after server reloads. This is achieved by creating a replication document in the `_replicator` database. ```APIDOC ## POST /db/replication/enable ### Description Sets up continuous replication that survives server restarts by creating a document in the `_replicator` database. ### Method POST ### Endpoint `/db/replication/enable` ### Parameters #### Path Parameters - **source** (string) - Required - The name of the source database or URL. - **target** (string) - Required - The name of the target database or URL. #### Query Parameters - **opts** (object) - Optional - Options for replication. - **create_target** (boolean) - Optional - If true, creates the target database if it doesn't exist. - **continuous** (boolean) - Optional - If true, enables continuous replication. ### Request Example ```javascript const response = await nano.db.replication.enable( 'source-db', 'http://admin:password@otherhost.com:5984/target-db', { create_target: true, continuous: true } ); ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the replication setup was successful. - **id** (string) - The ID of the created replication document. - **rev** (string) - The revision of the created replication document. #### Response Example ```json { "ok": true, "id": "replication-doc-id", "rev": "1-abc123" } ``` ``` -------------------------------- ### Compact CouchDB Database or Views with Nano Source: https://context7.com/apache/couchdb-nano/llms.txt Trigger database compaction to reclaim disk space using `nano.db.compact`. Optionally, compact views for a specific design document. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); // Compact database await nano.db.compact('mydb'); ``` ```javascript await nano.db.compact('mydb', 'my-design-doc'); // Output: { ok: true } ``` -------------------------------- ### Get Database Changes as Stream Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieves the changes feed for a database as a stream, piping the output to `process.stdout`. This is an alternative to `nano.db.changes` for real-time updates. ```javascript nano.db.changes('alice').pipe(process.stdout); ``` -------------------------------- ### Create Index Source: https://github.com/apache/couchdb-nano/blob/main/README.md Define and create an index on database fields using `alice.createIndex(indexDef)`. The `indexDef` object specifies the fields to index and the index name. ```js const indexDef = { index: { fields: ['foo'] }, name: 'fooindex' }; const response = await alice.createIndex(indexDef) ``` -------------------------------- ### Get Database Changes Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves a list of changes that have occurred in a database since a specified sequence number. This can include document updates and deletions. ```APIDOC ## GET /db/changes ### Description Returns the changes feed for a database as a single response containing all changes since a given sequence. ### Method GET ### Endpoint `/db/changes` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the database to get changes from. #### Query Parameters - **params** (object) - Optional - Parameters for filtering or modifying the changes feed. - **since** (string) - Optional - The sequence number to start retrieving changes from. Defaults to the latest sequence. - **include_docs** (boolean) - Optional - If true, includes the full document for each change. - **limit** (number) - Optional - The maximum number of changes to return. ### Request Example ```javascript const changes = await nano.db.changes('mydb'); const changes = await nano.db.changes('mydb', { since: '5-ghi', include_docs: true, limit: 100 }); ``` ### Response #### Success Response (200) - **results** (array) - An array of change objects. - **seq** (string) - The sequence number of the change. - **id** (string) - The ID of the changed document. - **changes** (array) - An array of revisions for the change. - **rev** (string) - The revision ID. - **last_seq** (string) - The last sequence number in the feed. - **pending** (number) - The number of pending changes. #### Response Example ```json { "results": [ { "seq": "1-abc", "id": "doc1", "changes": [{ "rev": "1-xyz" }] }, { "seq": "2-def", "id": "doc2", "changes": [{ "rev": "1-uvw" }] } ], "last_seq": "2-def", "pending": 0 } ``` ``` -------------------------------- ### Create New Release for Nano Source: https://github.com/apache/couchdb-nano/blob/main/README.md Follow these commands to create a new release for the nano package. Ensure you are on the main branch before proceeding. This process involves updating the version, pushing tags, and publishing to npm. ```sh npm version {patch|minor|major} ``` ```sh github push origin main --tags ``` ```sh npm publish ``` -------------------------------- ### Stream View Results Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.viewAsStream` to get view results as a stream, which is efficient for large datasets. Handle errors and pipe the stream to a destination. ```javascript alice.viewAsStream('characters', 'happy_ones', {reduce: false}) .on('error', (e) => console.error('error', e)) .pipe(process.stdout); ``` -------------------------------- ### Call a View with Specific Keys Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.view` to query a view with a specific set of keys. Ensure the view and design document exist. ```javascript const body = await alice.view('characters', 'happy_ones', { key: 'Tea Party', include_docs: true }) body.rows.forEach((doc) => { console.log(doc.value) }) ``` ```javascript const body = await alice.view('characters', 'soldiers', { keys: ['Hearts', 'Clubs'] }) ``` -------------------------------- ### Get Document by ID Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves a document using its ID. Supports options to include revision information, conflicts, attachments, or fetch a specific revision. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const db = nano.use('mydb'); // Simple get const doc = await db.get('mydoc'); console.log(doc); // Get with options const doc = await db.get('mydoc', { revs_info: true, conflicts: true }); // Get specific revision const doc = await db.get('mydoc', { rev: '1-abc123' }); // Get with attachments const doc = await db.get('mydoc', { attachments: true }); ``` -------------------------------- ### POST /db/use Source: https://context7.com/apache/couchdb-nano/llms.txt Returns a database object scoped to the specified database name, allowing you to perform document-level operations. ```APIDOC ## POST /db/use Returns a database object scoped to the specified database name, allowing you to perform document-level operations. ### Method POST ### Endpoint `/db/use` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the database to use. ### Request Example ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const alice = nano.use('alice'); // or: const alice = nano.db.use('alice'); // or: const alice = nano.scope('alice'); // Now use alice for document operations const doc = await alice.get('rabbit'); ``` ``` -------------------------------- ### Get CouchDB Database Information with Nano Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieve metadata about a specific database, such as document count, disk size, and update sequence, using `nano.db.get`. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const info = await nano.db.get('mydb'); console.log(info); // Output: // { // db_name: 'mydb', // doc_count: 42, // doc_del_count: 3, // update_seq: '45-g1AAAABXeJzL...', // disk_size: 12345, // sizes: { active: 1234, external: 2345, file: 12345 }, // compact_running: false // } ``` -------------------------------- ### Use a Pre-existing Undici Agent Source: https://github.com/apache/couchdb-nano/blob/main/README.md Provide a pre-configured undici.Agent instance to Nano for managing connections and timeouts. ```javascript const agent = new undici.Agent({bodyTimeout: 30000 }) const nano = Nano({ url: 'http://127.0.0.1:5984', agentOptions: agent }) ``` -------------------------------- ### Stream List Function Results Source: https://github.com/apache/couchdb-nano/blob/main/README.md Use `db.viewWithListAsStream` to get the results of a list function applied to a view as a stream. This is suitable for processing large, transformed datasets. ```javascript alice.viewWithListAsStream('characters', 'happy_ones', 'my_list') .on('error', (e) => console.error('error', e)) .pipe(process.stdout); ``` -------------------------------- ### Insert Document into Partitioned Database Source: https://github.com/apache/couchdb-nano/blob/main/README.md Insert documents into a partitioned database using `db.insert`. Ensure the document's `_id` follows the `:` format. ```javascript const doc = { _id: 'canidae:dog', name: 'Dog', latin: 'Canis lupus familiaris' } await db.insert(doc) ``` -------------------------------- ### Extend Nano with Custom Request Function Source: https://github.com/apache/couchdb-nano/blob/main/README.md Add custom functionality to Nano by utilizing the `nano.request` method. This example shows how to create a function to retrieve a specific revision of a document. ```javascript function getrabbitrev(rev) { return nano.request({ db: 'alice', doc: 'rabbit', method: 'get', params: { rev: rev } }); } getrabbitrev('4-2e6cdc4c7e26b745c2881a24e0eeece2').then((body) => { console.log(body); }); ``` -------------------------------- ### Fetch Revisions with db.fetchRevs() Source: https://context7.com/apache/couchdb-nano/llms.txt Use db.fetchRevs() to get revision information for multiple documents without fetching their full bodies. Similar to `db.fetch`, it can report 'not_found' for missing documents. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const db = nano.use('mydb'); const result = await db.fetchRevs({ keys: ['doc1', 'doc2', 'doc3'] }); console.log(result); // Output: // { // total_rows: 100, // offset: 0, // rows: [ // { id: 'doc1', key: 'doc1', value: { rev: '1-abc' } }, // { id: 'doc2', key: 'doc2', value: { rev: '1-def' } }, // { key: 'doc3', error: 'not_found' } // ] // } ``` -------------------------------- ### List Documents as Stream Source: https://github.com/apache/couchdb-nano/blob/main/README.md Retrieve all documents from a database as a stream using `alice.listAsStream()`. This is useful for large datasets and can be piped to other streams. ```js alice.listAsStream() .on('error', (e) => console.error('error', e)) .pipe(process.stdout) ``` -------------------------------- ### Get CouchDB Server Info Source: https://context7.com/apache/couchdb-nano/llms.txt Retrieves essential metadata about the CouchDB server, including its version, build details, and supported features. This is useful for checking server status and capabilities. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); const info = await nano.info(); console.log(info); ``` -------------------------------- ### List Documents Source: https://github.com/apache/couchdb-nano/blob/main/README.md List all documents in a database using `alice.list()`. The response contains document metadata, and `rows.forEach` can be used to iterate. ```js const doclist = await alice.list().then((body)=>{ body.rows.forEach((doc) => { console.log(doc); }) }); ``` -------------------------------- ### Make Custom HTTP Request Source: https://context7.com/apache/couchdb-nano/llms.txt Performs custom HTTP requests to CouchDB endpoints not covered by standard methods. Supports GET, POST, and other methods with request bodies and query parameters. ```javascript const nano = require('nano')('http://127.0.0.1:5984'); // Custom GET request const result = await nano.request({ db: 'mydb', doc: 'mydoc', method: 'GET', qs: { rev: '1-abc123' } }); // Custom POST request const result = await nano.request({ db: 'mydb', path: '_find', method: 'POST', body: { selector: { type: 'user' } } }); ``` -------------------------------- ### db.partitionedFind(partitionKey, query) Source: https://context7.com/apache/couchdb-nano/llms.txt Executes a Mango query scoped to a specific partition for better performance. ```APIDOC ## POST /dbName/partitionKey/_find ### Description Executes a Mango query scoped to a specific partition for better performance. ### Method POST ### Endpoint `/{dbName}/{partitionKey}/_find` ### Parameters #### Path Parameters - **partitionKey** (string) - Required - The key of the partition to query within. #### Request Body - **selector** (object) - Required - The query selector. - **fields** (array) - Optional - An array of fields to return. ### Request Example ```json { "selector": { "species": "wolf" }, "fields": [ "_id", "name", "habitat" ] } ``` ### Response #### Success Response (200) - **docs** (array) - An array of documents matching the query. #### Response Example ```json { "docs": [ { "_id": "canidae:wolf1", "name": "Gray Wolf", "habitat": "forest" } ] } ``` ``` -------------------------------- ### Stream Documents from a Partition Source: https://github.com/apache/couchdb-nano/blob/main/README.md Fetch documents from a partition as a stream using `nano.db.partitionedListAsStream(partitionKey, [params])`. This is useful for processing large datasets efficiently. ```javascript // fetch document id/revs from a partition nano.db.partitionedListAsStream('canidae') .on('error', (e) => console.error('error', e)) .pipe(process.stdout) // add document bodies but limit size of response nano.db.partitionedListAsStream('canidae', { include_docs: true, limit: 5 }) .on('error', (e) => console.error('error', e)) .pipe(process.stdout) ```