{"id":16620,"library":"fh-db","title":"FeedHenry Database Library","description":"The `fh-db` library, currently at version `3.3.2`, provides a robust database abstraction layer for Node.js applications, specifically designed to interface with MongoDB. It offers a \"Ditch-like\" API, aiming for a consistent set of actions and parameters that simplify common database operations such as create, read, update, and delete. This library functions as a wrapper around the native `mongodb` driver, abstracting some of its complexities and providing a higher-level interface suitable for FeedHenry cloud application development. While its original target Node.js engine was `4.4`, it has been updated to its current major version `3`, indicating that it received active development and maintenance at some point. Its key differentiator is providing a simplified, consistent API tailored for the FeedHenry ecosystem, reducing boilerplate when interacting with MongoDB. The latest publish date for version `3.3.2` was over 7 years ago, suggesting it is now in maintenance mode, though still widely used within the FeedHenry ecosystem.","status":"maintenance","version":"3.3.2","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/feedhenry/fh-db","tags":["javascript"],"install":[{"cmd":"npm install fh-db","lang":"bash","label":"npm"},{"cmd":"yarn add fh-db","lang":"bash","label":"yarn"},{"cmd":"pnpm add fh-db","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for database interactions; `fh-db` acts as a wrapper around the native MongoDB driver.","package":"mongodb","optional":false}],"imports":[{"note":"The library is primarily a CommonJS module, as indicated by its Node.js 4.4 engine requirement and typical usage patterns.","wrong":"import fhdb from 'fh-db';","symbol":"fhdb","correct":"const fhdb = require('fh-db');"},{"note":"The `db` method initializes and returns a database client instance, typically expecting a MongoDB connection URI. This instance then exposes the Ditch-like API for CRUD operations.","symbol":"dbInstance","correct":"const dbInstance = fhdb.db(process.env.MONGO_URI || 'mongodb://localhost:27017/mydatabase');"},{"note":"Database instances returned by `fhdb.db()` expose methods like `create`, `read`, `update`, `delete`, and `list` through a callback-based interface.","symbol":"CRUD operations","correct":"dbInstance.create('mycollection', { name: 'test' }, (err, data) => {});"}],"quickstart":{"code":"const fhdb = require('fh-db');\nconst assert = require('assert');\n\nconst MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/testdb_fhdb';\n\nasync function runExample() {\n  let dbInstance;\n  try {\n    dbInstance = fhdb.db(MONGO_URI);\n    console.log('Database connected to:', MONGO_URI);\n\n    const collectionName = 'mydata';\n    const documentToInsert = { id: 'item1', value: 'hello world', timestamp: new Date() };\n\n    // Create a document\n    console.log('Creating document...');\n    const createResult = await new Promise((resolve, reject) => {\n      dbInstance.create(collectionName, documentToInsert, (err, data) => {\n        if (err) return reject(err); resolve(data);\n      });\n    });\n    console.log('Created:', createResult);\n    assert.strictEqual(createResult.value, documentToInsert.value, 'Document created successfully');\n\n    // Read documents\n    console.log('Reading documents...');\n    const readResult = await new Promise((resolve, reject) => {\n      dbInstance.read(collectionName, { id: 'item1' }, (err, data) => {\n        if (err) return reject(err); resolve(data);\n      });\n    });\n    console.log('Read:', readResult);\n    assert(Array.isArray(readResult) && readResult.length > 0, 'Document should be found');\n\n    // Update a document\n    console.log('Updating document...');\n    const updatedValue = 'updated value';\n    const updateResult = await new Promise((resolve, reject) => {\n      dbInstance.update(collectionName, { id: 'item1' }, { value: updatedValue }, (err, data) => {\n        if (err) return reject(err); resolve(data);\n      });\n    });\n    console.log('Updated:', updateResult);\n    assert.strictEqual(updateResult.value, updatedValue, 'Document updated successfully');\n\n    // List all documents (simple read without query)\n    console.log('Listing all documents...');\n    const listResult = await new Promise((resolve, reject) => {\n      dbInstance.list(collectionName, (err, data) => {\n        if (err) return reject(err); resolve(data);\n      });\n    });\n    console.log('Listed:', listResult);\n    assert(Array.isArray(listResult), 'List should return an array');\n\n    // Delete a document\n    console.log('Deleting document...');\n    const deleteResult = await new Promise((resolve, reject) => {\n      dbInstance.delete(collectionName, { id: 'item1' }, (err, data) => {\n        if (err) return reject(err); resolve(data);\n      });\n    });\n    console.log('Deleted:', deleteResult);\n    assert.strictEqual(deleteResult.id, 'item1', 'Document deleted successfully');\n\n    // Verify deletion\n    const verifyDeletion = await new Promise((resolve, reject) => {\n      dbInstance.read(collectionName, { id: 'item1' }, (err, data) => {\n        if (err) return reject(err); resolve(data);\n      });\n    });\n    assert.strictEqual(verifyDeletion.length, 0, 'Document should no longer exist');\n\n  } catch (error) {\n    console.error('An error occurred:', error.message);\n  } finally {\n    // fh-db itself doesn't expose a direct close method; it relies on the underlying MongoDB driver's connection pooling.\n    console.log('Example finished. Ensure your MongoDB connection is managed appropriately by the underlying driver.');\n  }\n}\n\nrunExample();","lang":"javascript","description":"This quickstart demonstrates how to initialize `fh-db` with a MongoDB connection URI and perform basic CRUD (Create, Read, Update, Delete) and list operations on a collection. It uses Promises to wrap the callback-based API for easier asynchronous handling. Ensure a MongoDB instance is running and accessible via the provided `MONGO_URI`."},"warnings":[{"fix":"Before starting your MongoDB 3.x+ instance, use the `mongo` shell to update the authentication schema and create users. For example: `use admin; db.system.users.remove({}); db.system.version.remove({}); db.system.version.insert({ \"_id\" : \"authSchema\", \"currentVersion\" : 3 });` then restart Mongo and create users like `db.createUser({user: 'admin', pwd: 'admin', roles: ['root']})` and `db.createUser({user: 'ditchuser', pwd: 'ditchpassword', roles: ['dbAdmin']})`.","message":"When upgrading MongoDB to version 3.x or newer, the authentication schema changes significantly. Existing `fh-db` installations configured with older MongoDB versions (pre-3.x) will encounter authentication failures.","severity":"breaking","affected_versions":"All versions of `fh-db` when used with MongoDB Server >= 3.0.0."},{"fix":"Always use `const fhdb = require('fh-db');` for importing the module in Node.js applications to ensure compatibility. If an ESM module needs to use `fh-db`, consider dynamically `import()`ing it or wrapping it in a CommonJS bridge.","message":"`fh-db` is primarily a CommonJS module and was developed with older Node.js versions (specifically 4.4) in mind. While it might work with newer Node.js versions, direct ESM `import` statements may not function without a transpilation step or a specific Node.js configuration (e.g., `\"type\": \"module\"` in `package.json` for the consumer module, and then dynamic `import()`).","severity":"gotcha","affected_versions":"All versions when attempting ESM imports in newer Node.js environments."},{"fix":"Check `fh-db`'s `package.json` for its `mongodb` dependency range. If facing issues, try aligning your installed `mongodb` version with `fh-db`'s expected range. For new projects, consider using the native `mongodb` driver directly for better compatibility with the latest MongoDB server features and security updates.","message":"The `fh-db` library wraps the `mongodb` driver, which has undergone significant API changes across its major versions (e.g., v3 to v4 to v5). The `fh-db` library's last publish was 7 years ago, implying it likely uses an older version of the underlying `mongodb` driver. This could lead to compatibility issues with very recent MongoDB server versions (8.x+), or it may not expose the latest driver features.","severity":"deprecated","affected_versions":"All versions of `fh-db` when used with newer `mongodb` driver versions or MongoDB Server >= 4.x/5.x/6.x/7.x/8.x."}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify that your MongoDB connection URI includes the correct username and password. If using MongoDB 3.x+ and migrating from an older setup, ensure the authentication schema has been upgraded and users recreated as described in the warnings.","cause":"Incorrect MongoDB user credentials, or an outdated authentication schema (e.g., connecting a MongoDB 3.x+ server with users created for MongoDB 2.6 without upgrading the auth schema).","error":"Authentication failed."},{"fix":"Ensure you are using `const fhdb = require('fh-db');` at the top of your file. Verify that `fh-db` is correctly installed and accessible in `node_modules`.","cause":"The `fh-db` module was not correctly imported or initialized. This can happen if attempting an ESM `import` or if `require('fh-db')` somehow returns an empty or unexpected object.","error":"TypeError: fhdb.db is not a function"},{"fix":"Ensure your connection string points to the correct database (e.g., `fh-ditch`) for the provided user credentials, and that the user (e.g., `ditchuser`) has appropriate roles (`dbAdmin`) for that database. Test login using `mongo <dbname> -u <user> -p <password>` to confirm credentials and permissions.","cause":"Similar to 'Authentication failed', this specific error often indicates issues with the MongoDB user roles or the database the user is trying to access. The `ditchuser` mentioned in the README is set up for the `fh-ditch` database, not `admin` or other databases by default.","error":"MongoError: auth failed"}],"ecosystem":"npm"}