### Example OPTIONS Request Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt An example of an HTTP request using the OPTIONS method with the asterisk wildcard for the Request-URI, targeting the server itself. ```http OPTIONS * HTTP/1.1 ``` -------------------------------- ### Example GET Request to Origin Server Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt An example of an HTTP GET request sent directly to an origin server, using an absolute path and a Host header. ```http GET /pub/WWW/TheProject.html HTTP/1.1 Host: www.w3.org ``` -------------------------------- ### Example GET Request with Absolute URI (Proxy) Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt An example of an HTTP GET request using the absolute URI form, typically sent to a proxy server. ```http GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1 ``` -------------------------------- ### Install and Import Seald NeDB Source: https://github.com/seald/nedb/blob/master/README.md Installs the '@seald-io/nedb' package using npm and demonstrates how to require the Datastore module in a JavaScript project. ```bash npm install @seald-io/nedb ``` ```javascript const Datastore = require('@seald-io/nedb') ``` -------------------------------- ### HTTP Method Tokens Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt Lists the standard HTTP method tokens, including common methods like GET and POST, and the concept of extension methods. ```text Method = "OPTIONS" ; Section 9.2 | "GET" ; Section 9.3 | "HEAD" ; Section 9.4 | "POST" ; Section 9.5 | "PUT" ; Section 9.6 | "DELETE" ; Section 9.7 | "TRACE" ; Section 9.8 | "CONNECT" ; Section 9.9 | extension-method extension-method = token ``` -------------------------------- ### HTTP Cache-Control: Cache Extension Example Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt Demonstrates how to extend the 'Cache-Control' header with custom directives, such as a hypothetical 'community' extension modifying the 'private' directive. This allows for more granular caching control without breaking compatibility with caches that do not understand the extension. ```http Cache-Control: private, community="UCI" ``` -------------------------------- ### Find Documents with Basic Queries using Promises - JavaScript Source: https://context7.com/seald/nedb/llms.txt Provides examples of querying documents using field matching, regular expressions, dot notation for nested objects, and finding single or all documents. This uses the Promise-based API and requires the '@seald-io/nedb' library. ```javascript const Datastore = require('@seald-io/nedb') const db = new Datastore() // Setup test data await db.insertAsync([ { _id: 'mars', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }, { _id: 'earth', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }, { _id: 'jupiter', planet: 'Jupiter', system: 'solar', inhabited: false }, { _id: 'omicron', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } } ]) // Find all documents matching a field const solarPlanets = await db.findAsync({ system: 'solar' }) // Returns: Mars, Earth, Jupiter // Find using regular expressions const planetsWithAr = await db.findAsync({ planet: /ar/i }) // Returns: Mars, Earth // Find with multiple conditions const inhabitedSolar = await db.findAsync({ system: 'solar', inhabited: true }) // Returns: Earth only // Find using dot notation for nested objects const twoGenders = await db.findAsync({ 'humans.genders': 2 }) // Returns: Earth // Find one document const earth = await db.findOneAsync({ _id: 'earth' }) // Returns single document or null if not found // Find all documents const allDocs = await db.findAsync({}) ``` -------------------------------- ### React Native Usage: NeDB with AsyncStorage Source: https://context7.com/seald/nedb/llms.txt Shows how to integrate NeDB into a React Native application, automatically utilizing AsyncStorage for persistence. The example covers database initialization, data insertion, querying, and updating, with data persisting across app restarts. ```javascript import Datastore from '@seald-io/nedb' import AsyncStorage from '@react-native-async-storage/async-storage' // NeDB automatically uses AsyncStorage in React Native environment const db = new Datastore({ filename: 'myapp.db', autoload: true }) await db.autoloadPromise // Works exactly like Node.js version const userId = await AsyncStorage.getItem('userId') await db.insertAsync({ userId, settings: { theme: 'dark', notifications: true }, lastSync: new Date() }) const userSettings = await db.findOneAsync({ userId }) console.log(userSettings.settings.theme) // 'dark' // Update settings await db.updateAsync( { userId }, { $set: { 'settings.notifications': false } }, {} ) // Data persists across app restarts ``` -------------------------------- ### Database Initialization Source: https://context7.com/seald/nedb/llms.txt Demonstrates how to create both in-memory and persistent datastores. ```APIDOC ## Database Initialization ### Description Initialize an in-memory datastore (non-persistent) or a file-based datastore with automatic or manual loading. ### Method `new Datastore([options])` ### Parameters #### Options Object - **filename** (string) - Optional - The path to the database file for persistent storage. - **autoload** (boolean) - Optional - If true, the database will automatically load its data when initialized. Defaults to false. ### Request Example ```javascript const Datastore = require('@seald-io/nedb') // In-memory database const inMemoryDb = new Datastore() // Persistent database with manual loading const manualDb = new Datastore({ filename: './data/users.db' }) await manualDb.loadDatabaseAsync() // Persistent database with automatic loading const autoDb = new Datastore({ filename: './data/products.db', autoload: true }) await autoDb.autoloadPromise // Wait for autoload to complete // Multiple collections const multiDb = { users: new Datastore({ filename: './data/users.db', autoload: true }), orders: new Datastore({ filename: './data/orders.db', autoload: true }) } await Promise.all([multiDb.users.autoloadPromise, multiDb.orders.autoloadPromise]) ``` ### Response N/A (Initialization does not return a response, but can throw errors during loading.) ### Error Handling - **loadDatabaseAsync()**: Throws an error if the database file cannot be loaded. - **autoload**: If `autoload` is true, errors during loading will be logged and the `autoloadPromise` will reject. ``` -------------------------------- ### Initialize Persistent Database with Promises - JavaScript Source: https://context7.com/seald/nedb/llms.txt Shows how to set up a file-based persistent datastore using the Promise-based API. It covers both manual and automatic database loading, including options for handling multiple collections. The '@seald-io/nedb' library is a dependency. ```javascript const Datastore = require('@seald-io/nedb') // Option 1: Manual loading const db1 = new Datastore({ filename: './data/users.db' }) try { await db1.loadDatabaseAsync() console.log('Database loaded successfully') } catch (error) { console.error('Failed to load database:', error) } // Option 2: Automatic loading (recommended) const db2 = new Datastore({ filename: './data/products.db', autoload: true }) // Wait for autoload to complete before using await db2.autoloadPromise // Option 3: Multiple collections with autoload const db = { users: new Datastore({ filename: './data/users.db', autoload: true }), orders: new Datastore({ filename: './data/orders.db', autoload: true }) } await Promise.all([db.users.autoloadPromise, db.orders.autoloadPromise]) ``` -------------------------------- ### HTTP GET Method Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt The GET method retrieves information identified by the Request-URI. It can be used for standard retrieval, conditional retrieval (using If-Modified-Since, etc.), or partial retrieval (using Range header). ```APIDOC ## GET /{resource_path} ### Description The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client. The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client. ### Method GET ### Endpoint /{resource_path} ### Parameters #### Path Parameters - **resource_path** (string) - Required - The path to the resource to be retrieved. #### Query Parameters None #### Headers - **If-Modified-Since** (string) - Optional - Used for conditional GET. - **If-Unmodified-Since** (string) - Optional - Used for conditional GET. - **If-Match** (string) - Optional - Used for conditional GET. - **If-None-Match** (string) - Optional - Used for conditional GET. - **If-Range** (string) - Optional - Used for conditional GET. - **Range** (string) - Optional - Used for partial GET (e.g., "bytes=0-499"). ### Request Example ```http GET /resource/123 HTTP/1.1 Host: example.com If-Modified-Since: Tue, 15 Nov 1994 12:45:26 GMT ``` ```http GET /resource/456 HTTP/1.1 Host: example.com Range: bytes=0-99 ``` ### Response #### Success Response (200 OK) - **Content-Type** (string) - The media type of the entity body. - **Content-Length** (integer) - The size of the entity body. - **Last-Modified** (string) - If the response is a representation of a resource that has been modified since the time specified in the "If-Modified-Since" header. - **ETag** (string) - An entity-tag is an identifier assigned by the origin server to a specific version of a resource for the purpose of comparing entity-tags. - (Entity body containing the requested resource) #### Partial Content Response (206 Partial Content) - **Content-Range** (string) - Indicates where in the full "entity" the partial content belongs. - **Content-Length** (integer) - The size of the partial content body. - **Content-Type** (string) - The media type of the entity body. - (Partial entity body) #### Not Modified Response (304 Not Modified) - (No response body) #### Response Example (200 OK) ```http HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1234 Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT ... ``` #### Response Example (206 Partial Content) ```http HTTP/1.1 206 Partial Content Content-Range: bytes 0-499/1234 Content-Length: 500 Content-Type: application/octet-stream ... ``` ``` -------------------------------- ### Initialize In-Memory Database with Promises - JavaScript Source: https://context7.com/seald/nedb/llms.txt Demonstrates how to create and use an in-memory database using the Promise-based API. This is useful for temporary data storage or testing where persistence is not required. It requires the '@seald-io/nedb' library. ```javascript const Datastore = require('@seald-io/nedb') // Create in-memory database const db = new Datastore() // Immediately ready to use - no loading required await db.insertAsync({ name: 'Alice', age: 25 }) const docs = await db.findAsync({ age: { $gte: 18 } }) console.log(docs) // [{ name: 'Alice', age: 25, _id: '...' }] ``` -------------------------------- ### 206 Partial Content Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt The server has fulfilled a partial GET request for the resource. ```APIDOC ## 206 Partial Content ### Description The server has fulfilled the partial GET request for the resource. The request MUST have included a Range header field indicating the desired range, and MAY have included an If-Range header field to make the request conditional. ### Method GET ### Endpoint Any valid endpoint ### Parameters #### Query Parameters None #### Headers - **Range** (string) - Required - The desired range of the resource. - **If-Range** (string) - Optional - Makes the request conditional. ### Request Example ``` GET /resource/example HTTP/1.1 Host: example.com Range: bytes=0-999 If-Range: "some-etag" ``` ### Response #### Success Response (206) - **Content-Range** (string) - Required - Indicates the range included with this response. - **Date** (string) - Required - The date and time the response was generated. - **ETag** (string) - Optional - Entity tag for the resource. - **Content-Location** (string) - Optional - URI identifying the specific variant. - **Expires** (string) - Optional - Date/time after which the response is considered stale. - **Cache-Control** (string) - Optional - Directives for caching mechanisms. - **Vary** (string) - Optional - Indicates which headers were used to determine the variant. #### Response Example ``` HTTP/1.1 206 Partial Content Date: Wed, 15 Jun 1999 20:18:05 GMT Content-Range: bytes 0-999/10000 Content-Length: 1000 Content-Type: application/octet-stream [...binary data...] ``` ``` -------------------------------- ### Changes from HTTP/1.0 Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt Summarizes major differences between HTTP/1.0 and HTTP/1.1, focusing on changes to simplify multi-homed servers and conserve IP addresses. ```APIDOC ## Changes from HTTP/1.0 ### Description This section highlights key changes introduced in HTTP/1.1 compared to HTTP/1.0, particularly those enhancing server multi-homing and IP address conservation. ### Method Not applicable (This is a protocol-level description). ### Endpoint Not applicable (This is a protocol-level description). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (200) - **Host Request Header**: Requirement for clients and servers to support and validate the Host header. - **Absolute URIs**: Acceptance of absolute URIs in requests. #### Response Example N/A ``` -------------------------------- ### HEAD Method Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt The HEAD method is identical to GET but the server MUST NOT return a message-body. It's used for obtaining metadata about a resource without transferring its body. ```APIDOC ## HEAD /resource ### Description Retrieves the headers associated with a resource without the response body. Useful for checking resource existence, modification time, or content type. ### Method HEAD ### Endpoint /resource ### Parameters None ### Request Example None ### Response #### Success Response (200 OK) - **Headers** (object) - Contains metadata about the resource, similar to a GET request but without the body. #### Response Example ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1234 Last-Modified: Mon, 20 Oct 1997 17:00:00 GMT ``` ``` -------------------------------- ### Pragma Header Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. The 'no-cache' directive is a common example. ```APIDOC ## Pragma Header ### Description Includes implementation-specific directives applicable to recipients in the request/response chain. The 'no-cache' directive instructs to forward the request even if a cached copy exists. ### Method Request/Response Header ### Endpoint N/A ### Parameters #### Request/Response Headers - **Pragma** (pragma-directive) - Optional - Directives such as 'no-cache'. ### Request Example ``` Pragma: no-cache ``` ### Response #### Success Response (200) - **Pragma** (pragma-directive) - Optional - Directives from the server. #### Response Example ``` Pragma: no-cache ``` ``` -------------------------------- ### Query Example with $where (JavaScript) Source: https://github.com/seald/nedb/blob/master/API.md Demonstrates the use of the $where operator in NeDB queries. This allows for custom filtering logic using JavaScript functions within the query. The function receives the document as 'this' and should return a boolean. ```javascript { $where: function () { // object is 'this' // return a boolean } } ``` -------------------------------- ### Drop NeDB Database Source: https://github.com/seald/nedb/blob/master/README.md Demonstrates how to completely remove a NeDB database using the `dropDatabaseAsync` method. It includes an example of inserting a document before dropping and verifying the database is empty afterward. ```javascript const Datastore = require('@seald-io/nedb') const db = new Datastore() await d.insertAsync({ hello: 'world' }) await d.dropDatabaseAsync() // assert.equal(d.getAllData().length, 0) // assert.equal(await exists(testDb), false) // Note: assertions are commented out as they require additional setup. ``` -------------------------------- ### Browser Bundle Usage with NeDB Source: https://github.com/seald/nedb/blob/master/README.md Shows how to include and use the NeDB browser bundle in an HTML file. It demonstrates creating an in-memory datastore and performing basic insert and find operations using the global `Nedb` object. ```html ``` -------------------------------- ### If-Modified-Since Header Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt The If-Modified-Since request-header field is used to make a GET request conditional. If the requested resource has not been modified since the date specified in the header, the server returns a 304 (Not Modified) status code without a message body. ```APIDOC ## GET /resource ### Description Retrieve a resource only if it has been modified since a specific date. Useful for cache validation. ### Method GET ### Endpoint /resource ### Parameters #### Header Parameters - **If-Modified-Since** (string) - Required - A date string in HTTP-date format (e.g., 'Sat, 29 Oct 1994 19:43:31 GMT'). ### Request Example ``` GET /resource HTTP/1.1 Host: example.com If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT ``` ### Response #### Success Response (200 OK) - **entity-body** (any) - The representation of the resource if it has been modified. #### Success Response (304 Not Modified) - **No response body** - Returned if the resource has not been modified since the specified date. #### Response Example (200 OK) { "data": "updated resource content" } #### Response Example (304 Not Modified) (No content) ``` -------------------------------- ### Create and Load NeDB Datastores Source: https://github.com/seald/nedb/blob/master/README.md Illustrates three ways to create NeDB datastores: in-memory only, persistent with manual loading, and persistent with automatic loading. It also shows how to manage multiple collections. ```javascript // Type 1: In-memory only datastore (no need to load the database) const Datastore = require('@seald-io/nedb') const db = new Datastore() ``` ```javascript // Type 2: Persistent datastore with manual loading const Datastore = require('@seald-io/nedb') const db = new Datastore({ filename: 'path/to/datafile' }) try { await db.loadDatabaseAsync() } catch (error) { // loading has failed } // loading has succeeded ``` ```javascript // Type 3: Persistent datastore with automatic loading const Datastore = require('@seald-io/nedb') const db = new Datastore({ filename: 'path/to/datafile', autoload: true }) // You can await db.autoloadPromise to catch a potential error when autoloading. // You can issue commands right away ``` ```javascript // Managing multiple datastores (collections) db = {} db.users = new Datastore('path/to/users.db') db.robots = new Datastore('path/to/robots.db') // You need to load each database await db.users.loadDatabaseAsync() await db.robots.loadDatabaseAsync() ``` -------------------------------- ### HTTP Connection Header Usage Example Source: https://github.com/seald/nedb/blob/master/test/byline/rfc.txt Illustrates how the 'Connection' header is used to signal specific options for a connection. For instance, 'close' indicates the connection should be terminated after the response. Proxies must remove headers listed in the Connection header before forwarding. ```http Connection: close ``` -------------------------------- ### HTTP Methods Source: https://github.com/seald/nedb/blob/master/test/byline/rfc_huge.txt Lists the standard HTTP methods and the possibility of extension methods. It also mentions the case-sensitivity of methods and server responsibilities for handling them. ```text Method = "OPTIONS" ; Section 9.2 | "GET" ; Section 9.3 | "HEAD" ; Section 9.4 | "POST" ; Section 9.5 | "PUT" ; Section 9.6 | "DELETE" ; Section 9.7 | "TRACE" ; Section 9.8 | "CONNECT" ; Section 9.9 | extension-method extension-method = token ``` -------------------------------- ### Browser Usage: NeDB with Persistent Storage Source: https://context7.com/seald/nedb/llms.txt Demonstrates how to use NeDB in a browser environment with persistent storage enabled via localforage. It shows initialization, data insertion, querying, and counting, with data persisting across page reloads. ```html
``` -------------------------------- ### Cursor Constructor Source: https://github.com/seald/nedb/blob/master/API.md Creates a new cursor instance bound to a specific datastore and query. ```APIDOC ## new Cursor(db, query, [mapFn]) ### Description Creates a new cursor for the collection. ### Parameters #### Path Parameters - **db** (`Datastore`) - Required - The datastore this cursor is bound to. - **query** (`query`) - Required - The query this cursor will operate on. - **mapFn** (`mapFn`) - Optional - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove. ``` -------------------------------- ### Projection Example (JavaScript) Source: https://github.com/seald/nedb/blob/master/API.md Illustrates how to use projections in NeDB to specify which fields to include or exclude in query results. It follows MongoDB's syntax, using 1 for inclusion and 0 for exclusion. Nested fields can be targeted using dot notation. ```javascript { a: 1, b: 1 } ``` ```javascript { a: 0, b: 0 } ``` -------------------------------- ### Upsert with Modifier in NeDB Source: https://github.com/seald/nedb/blob/master/README.md This example shows how to perform an upsert operation where the update is defined using a modifier. If a document matching the query exists, it will be updated with the modifier. If not, a new document will be created based on the query and modified by the update operation. ```javascript // If you upsert with a modifier, the upserted doc is the query modified by the modifier // This is simpler than it sounds :) await db.updateAsync({ planet: 'Pluton' }, { $inc: { distance: 38 } }, { upsert: true }) // A new document { _id: 'id5', planet: 'Pluton', distance: 38 } has been added to the collection ```