### Quick Start Source: https://github.com/blackboardsh/goldfishdb/blob/main/readme.md Initialize and use GoldfishDB with a defined schema. ```APIDOC ## Quick Start Initialize and use GoldfishDB with a defined schema. ### Method ```typescript import DB from 'goldfishdb'; // Define your schema const schema = { v: 1, stores: { users: { type: "collection", schema: { name: { type: "string", required: true }, email: { type: "string", required: true }, age: { type: "number", required: false } } } } }; // Initialize database with default encryption const db = new DB().init({ schemaHistory: [{ v: 1, schema, migrationSteps: false }], db_folder: './data' }); // Or with custom passphrase for production const prodDb = new DB().init({ schemaHistory: [{ v: 1, schema, migrationSteps: false }], db_folder: './data', passphrase: 'your-production-secret' }); // Use the database const user = db.collection('users').insert({ name: "John Doe", email: "john@example.com", age: 30 }); const allUsers = db.collection('users').query(); const userById = db.collection('users').queryById(user.id); ``` ``` -------------------------------- ### Installation Source: https://github.com/blackboardsh/goldfishdb/blob/main/readme.md Install GoldfishDB using npm. ```APIDOC ## Installation Install GoldfishDB using npm. ### Method ```bash npm install goldfishdb ``` ``` -------------------------------- ### Install GoldfishDB via NPM Source: https://github.com/blackboardsh/goldfishdb/blob/main/readme.md The standard command to add the GoldfishDB package to your project dependencies. ```bash npm install goldfishdb ``` -------------------------------- ### Implement Schema Migrations for Database Evolution in GoldfishDB Source: https://context7.com/blackboardsh/goldfishdb/llms.txt This snippet illustrates how to define and apply schema migrations in GoldfishDB to manage database structure changes over time. It shows how to define multiple schema versions and corresponding migration steps, including adding new fields, modifying existing ones, and performing complex multi-step migrations. The example also demonstrates accessing database methods within migration functions. ```typescript import DB from 'goldfishdb'; const { collection, string, number, defaultOpts, schema } = DB.v1.schemaType; // Version 1 schema const schemaV1 = schema({ v: 1, stores: { users: collection({ name: string({ required: true, internal: false }), email: string({ required: true, internal: false }), }), }, }); // Version 2 schema - adds 'role' field const schemaV2 = schema({ v: 2, stores: { users: collection({ name: string({ required: true, internal: false }), email: string({ required: true, internal: false }), role: string(defaultOpts), // new field }), }, }); // Version 3 schema - converts role to number (roleLevel) const schemaV3 = schema({ v: 3, stores: { users: collection({ name: string({ required: true, internal: false }), email: string({ required: true, internal: false }), roleLevel: number(defaultOpts), // changed from string role to number }), }, }); // Define migrations const migrationsV2 = [{ users: (doc, db, targetSchema) => { doc.role = 'user'; // Set default role for existing users }, }]; const migrationsV3 = [{ users: (doc, db, targetSchema) => { // Convert role string to roleLevel number const roleMap = { admin: 3, moderator: 2, user: 1 }; doc.roleLevel = roleMap[doc.role] || 1; delete doc.role; }, }]; // Initialize with full migration history const db = new DB().init({ schemaHistory: [ { v: 1, schema: schemaV1, migrationSteps: false }, { v: 2, schema: schemaV2, migrationSteps: migrationsV2 }, { v: 3, schema: schemaV3, migrationSteps: migrationsV3 }, ], db_folder: './data', }); // Multi-step migration within a single version const complexMigration = [{ users: (doc, db, targetSchema) => { // Step 1: normalize email doc.email = doc.email.toLowerCase(); }, }, { users: (doc, db, targetSchema) => { // Step 2: additional processing after all docs normalized doc.emailDomain = doc.email.split('@')[1]; }, }]; // Access database methods within migrations const migrationWithDbAccess = [{ users: (doc, db, targetSchema) => { // Can query other collections during migration const allUsers = db.collection('users').query(); // Can even remove documents during migration if (doc.email.includes('test')) { db.collection('users').remove(doc.id); } }, }]; ``` -------------------------------- ### Retrieving Documents by ID Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Shows how to fetch a specific document using its ID with collection().queryById(). Includes examples for field selection and overriding private field visibility. ```typescript import DB from 'goldfishdb'; const { collection, string, number, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { users: collection({ name: string({ required: true, internal: false }), email: string({ required: true, internal: false }), password: string({ ...defaultOpts, private: true }), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); // Query by ID const result = db.collection('users').queryById('users.1'); // Select specific fields const partial = db.collection('users').queryById('users.1', { select: ['name', 'id'], }); // Include private fields explicitly const withPrivate = db.collection('users').queryById('users.1', { includePrivate: true, }); ``` -------------------------------- ### Define Strongly-Typed Collection Schemas with GoldfishDB Source: https://context7.com/blackboardsh/goldfishdb/llms.txt This snippet demonstrates how to define a strongly-typed collection schema using GoldfishDB's schema type factories. It covers various field types like string, number, boolean, object, array, record, and ref, along with options for required fields and default values. The example also shows how to initialize the database with the defined schema and insert data. ```typescript import DB from 'goldfishdb'; const { collection, string, number, boolean, object, array, record, ref, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { // Collection with various field types profiles: collection({ username: string({ required: true, internal: false }), bio: string(defaultOpts), followerCount: number({ required: true, internal: false }), isVerified: boolean(defaultOpts), // Nested object settings: object({ theme: string(defaultOpts), notifications: boolean(defaultOpts), }, defaultOpts), // Array of strings tags: array(string(defaultOpts), defaultOpts), // Record (key-value object with arbitrary string keys) metadata: record({ value: string(defaultOpts), }, defaultOpts), }), // Collection with references to other collections comments: collection({ text: string({ required: true, internal: false }), authorId: ref(['profiles'], { required: true, internal: false }), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); // Insert profile with nested structures const profile = db.collection('profiles').insert({ username: 'developer', bio: 'Building cool things', followerCount: 100, isVerified: true, settings: { theme: 'dark', notifications: true, }, tags: ['typescript', 'nodejs', 'databases'], metadata: { github: { value: 'https://github.com/dev' }, twitter: { value: '@developer' }, }, }); console.log(profile.settings?.theme); // 'dark' console.log(profile.tags?.[0]); // 'typescript' ``` -------------------------------- ### Initialize GoldfishDB Instance Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Demonstrates how to define a schema and initialize the database in development, production (with encryption), and testing (in-memory) modes. ```typescript import DB from 'goldfishdb'; const { collection, string, number, boolean, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { users: collection({ name: string({ required: true, internal: false }), email: string({ required: true, internal: false }), age: number(defaultOpts), isActive: boolean(defaultOpts), }), posts: collection({ title: string({ required: true, internal: false }), content: string({ required: true, internal: false }), authorId: string({ required: true, internal: false }), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); const prodDb = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', passphrase: process.env.DB_SECRET, }); const testDb = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], engine: 'none', initialData: undefined, }); ``` -------------------------------- ### Initialize and Use GoldfishDB Source: https://github.com/blackboardsh/goldfishdb/blob/main/readme.md Demonstrates how to define a schema, initialize the database instance with optional encryption, and perform basic CRUD operations like inserting and querying documents. ```typescript import DB from 'goldfishdb'; const schema = { v: 1, stores: { users: { type: "collection", schema: { name: { type: "string", required: true }, email: { type: "string", required: true }, age: { type: "number", required: false } } } } }; const db = new DB().init({ schemaHistory: [{ v: 1, schema, migrationSteps: false }], db_folder: './data' }); const user = db.collection('users').insert({ name: "John Doe", email: "john@example.com", age: 30 }); const allUsers = db.collection('users').query(); const userById = db.collection('users').queryById(user.id); ``` -------------------------------- ### Querying Collections with Filters, Sorting, and Selection Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Demonstrates how to use the collection().query() method to retrieve documents. It supports filtering via where clauses, sorting, result limiting, and field selection to optimize data retrieval. ```typescript import DB from 'goldfishdb'; const { collection, string, number, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { products: collection({ name: string({ required: true, internal: false }), price: number({ required: true, internal: false }), category: string(defaultOpts), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); // Insert sample data db.collection('products').insert({ name: 'Laptop', price: 999, category: 'Electronics' }); db.collection('products').insert({ name: 'Phone', price: 699, category: 'Electronics' }); db.collection('products').insert({ name: 'Desk', price: 299, category: 'Furniture' }); db.collection('products').insert({ name: 'Chair', price: 199, category: 'Furniture' }); // Query all documents const allProducts = db.collection('products').query(); // Filter with where clause const electronics = db.collection('products').query({ where: (doc) => doc.category === 'Electronics', }); // Sort by price descending const sortedProducts = db.collection('products').query({ sort: (a, b) => b.price - a.price, }); // Limit results const topTwo = db.collection('products').query({ where: (doc) => doc.category === 'Electronics', sort: (a, b) => b.price - a.price, limit: 2, }); // Select specific fields only const namesAndPrices = db.collection('products').query({ select: ['name', 'price', 'id'], }); ``` -------------------------------- ### Insert Documents into Collections Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Shows how to insert documents into a defined collection. The database automatically handles ID generation and timestamping, while TypeScript enforces schema requirements. ```typescript import DB from 'goldfishdb'; const { collection, string, number, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { users: collection({ name: string({ required: true, internal: false }), email: string({ required: true, internal: false }), age: number(defaultOpts), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); const user = db.collection('users').insert({ name: 'John Doe', email: 'john@example.com', age: 30, }); const user2 = db.collection('users').insert({ name: 'Jane Smith', email: 'jane@example.com', }); ``` -------------------------------- ### Database Operations Source: https://github.com/blackboardsh/goldfishdb/blob/main/readme.md Perform basic operations on collections within GoldfishDB. ```APIDOC ## Database Operations Perform basic operations on collections within GoldfishDB. ### Insert Document Inserts a new document into a collection. ### Method ```typescript db.collection('collectionName').insert(document: object) ``` ### Query All Documents Retrieves all documents from a collection. ### Method ```typescript db.collection('collectionName').query() ``` ### Query Document by ID Retrieves a single document from a collection by its ID. ### Method ```typescript db.collection('collectionName').queryById(id: string) ``` ``` -------------------------------- ### Close GoldfishDB Connection with db.close() in TypeScript Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Demonstrates how to properly close a GoldfishDB database connection to ensure all pending writes are flushed and resources are cleaned up. This is crucial for graceful application shutdowns, especially when handling signals like SIGINT and SIGTERM. ```typescript import DB from 'goldfishdb'; const { collection, string, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { logs: collection({ message: string({ required: true, internal: false }), level: string(defaultOpts), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); // Perform operations db.collection('logs').insert({ message: 'Application started', level: 'info' }); db.collection('logs').insert({ message: 'Processing request', level: 'debug' }); // Close database (flushes pending writes, clears save interval) db.close(); // Handle graceful shutdown in applications process.on('SIGINT', () => { console.log('Shutting down...'); db.close(); process.exit(0); }); process.on('SIGTERM', () => { console.log('Terminating...'); db.close(); process.exit(0); }); ``` -------------------------------- ### Collection Query API Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Query documents from a collection with optional filtering, sorting, limiting, and field selection. The `where` function receives read-only documents for type-safe filtering. ```APIDOC ## Collection Query with `collection().query()` ### Description Query documents from a collection with optional filtering, sorting, limiting, and field selection. Returns an object with `data` array and `err` field. The `where` function receives read-only documents for type-safe filtering. ### Method GET (or POST depending on implementation, typically GET for queries) ### Endpoint `/api/collections/{collectionName}/query` (Conceptual endpoint, actual usage is via client library method) ### Parameters #### Query Parameters - **where** (function) - Optional - A function to filter documents. Receives a read-only document. - **sort** (function) - Optional - A function to sort documents. Receives two documents (a, b) and should return a number. - **limit** (number) - Optional - The maximum number of documents to return. - **select** (array of strings) - Optional - An array of field names to include in the results. ### Request Example ```typescript // Assuming 'db' is an initialized GoldfishDB instance const electronics = db.collection('products').query({ where: (doc) => doc.category === 'Electronics', sort: (a, b) => b.price - a.price, limit: 2, select: ['name', 'price', 'id'], }); ``` ### Response #### Success Response (200) - **data** (array) - An array of documents matching the query criteria. - **err** (object | null) - An error object if the query failed, otherwise null. #### Response Example ```json { "data": [ { "id": "products.1", "name": "Laptop", "price": 999 }, { "id": "products.2", "name": "Phone", "price": 699 } ], "err": null } ``` ``` -------------------------------- ### Query by ID API Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Retrieve a single document by its unique ID. Supports field selection and inclusion of private fields. ```APIDOC ## Query by ID with `collection().queryById()` ### Description Retrieve a single document by its unique ID. Returns an object with `data` (the document or null) and `err` field. Supports field selection to limit returned properties. ### Method GET ### Endpoint `/api/collections/{collectionName}/{documentId}` (Conceptual endpoint, actual usage is via client library method) ### Parameters #### Path Parameters - **collectionName** (string) - Required - The name of the collection. - **documentId** (string) - Required - The unique ID of the document to retrieve. #### Query Parameters - **select** (array of strings) - Optional - An array of field names to include in the results. - **includePrivate** (boolean) - Optional - If true, includes fields marked as private. ### Request Example ```typescript // Assuming 'db' is an initialized GoldfishDB instance const user = db.collection('users').queryById('users.1', { select: ['name', 'id'], includePrivate: true }); ``` ### Response #### Success Response (200) - **data** (object | null) - The document object if found, otherwise null. - **err** (object | null) - An error object if the query failed, otherwise null. #### Response Example ```json { "data": { "id": "users.1", "name": "Alice", "email": "alice@example.com", "password": "hashed_password_123" }, "err": null } ``` ``` -------------------------------- ### Update Document in GoldfishDB Collection Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Updates an existing document in a collection by its ID using `collection().update()`. This method automatically updates the `date_updated` timestamp and returns the modified document. If the document ID does not exist, it returns null. It supports partial updates, preserving unchanged fields. ```typescript import DB from 'goldfishdb'; const { collection, string, number, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { tasks: collection({ title: string({ required: true, internal: false }), status: string({ required: true, internal: false }), priority: number(defaultOpts), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); // Insert a task const task = db.collection('tasks').insert({ title: 'Complete documentation', status: 'pending', priority: 1, }); console.log(task.date_updated); // undefined (never updated) // Update specific fields const updatedTask = db.collection('tasks').update('tasks.1', { status: 'in-progress', priority: 2, }); console.log(updatedTask?.status); // 'in-progress' console.log(updatedTask?.priority); // 2 console.log(updatedTask?.title); // 'Complete documentation' (unchanged) console.log(updatedTask?.date_updated); // 1699876600000 (auto-updated) // Update non-existent document returns null const result = db.collection('tasks').update('tasks.999', { status: 'done' }); console.log(result); // null // Partial update - only change one field const finalUpdate = db.collection('tasks').update('tasks.1', { status: 'completed', }); console.log(finalUpdate?.priority); // 2 (still preserved) ``` -------------------------------- ### Remove Document from GoldfishDB Collection Source: https://context7.com/blackboardsh/goldfishdb/llms.txt Removes a document from a collection by its ID using `collection().remove()`. It returns `true` if the removal was successful and `false` if the document did not exist. This function is useful for data cleanup and management. ```typescript import DB from 'goldfishdb'; const { collection, string, defaultOpts, schema } = DB.v1.schemaType; const appSchema = schema({ v: 1, stores: { notes: collection({ title: string({ required: true, internal: false }), content: string(defaultOpts), }), }, }); const db = new DB().init({ schemaHistory: [{ v: 1, schema: appSchema, migrationSteps: false }], db_folder: './data', }); // Insert notes db.collection('notes').insert({ title: 'Note 1', content: 'Content 1' }); db.collection('notes').insert({ title: 'Note 2', content: 'Content 2' }); db.collection('notes').insert({ title: 'Note 3', content: 'Content 3' }); // Verify count console.log(db.collection('notes').query().data.length); // 3 // Remove a document const removed = db.collection('notes').remove('notes.2'); console.log(removed); // true // Verify removal console.log(db.collection('notes').query().data.length); // 2 console.log(db.collection('notes').queryById('notes.2').data); // null // Try to remove non-existent document const notRemoved = db.collection('notes').remove('notes.999'); console.log(notRemoved); // false // Remaining documents const remaining = db.collection('notes').query(); console.log(remaining.data.map(n => n.id)); // ['notes.1', 'notes.3'] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.