Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
fhdb
✓ const fhdb = require('fh-db');
✗ import fhdb from 'fh-db';
The library is primarily a CommonJS module, as indicated by its Node.js 4.4 engine requirement and typical usage patterns.
dbInstance
✓ const dbInstance = fhdb.db(process.env.MONGO_URI || 'mongodb://localhost:27017/mydatabase');
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.
CRUD operations
✓ dbInstance.create('mycollection', { name: 'test' }, (err, data) => {});
Database instances returned by `fhdb.db()` expose methods like `create`, `read`, `update`, `delete`, and `list` through a callback-based interface.
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`.
const fhdb = require('fh-db');
const assert = require('assert');
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/testdb_fhdb';
async function runExample() {
let dbInstance;
try {
dbInstance = fhdb.db(MONGO_URI);
console.log('Database connected to:', MONGO_URI);
const collectionName = 'mydata';
const documentToInsert = { id: 'item1', value: 'hello world', timestamp: new Date() };
// Create a document
console.log('Creating document...');
const createResult = await new Promise((resolve, reject) => {
dbInstance.create(collectionName, documentToInsert, (err, data) => {
if (err) return reject(err); resolve(data);
});
});
console.log('Created:', createResult);
assert.strictEqual(createResult.value, documentToInsert.value, 'Document created successfully');
// Read documents
console.log('Reading documents...');
const readResult = await new Promise((resolve, reject) => {
dbInstance.read(collectionName, { id: 'item1' }, (err, data) => {
if (err) return reject(err); resolve(data);
});
});
console.log('Read:', readResult);
assert(Array.isArray(readResult) && readResult.length > 0, 'Document should be found');
// Update a document
console.log('Updating document...');
const updatedValue = 'updated value';
const updateResult = await new Promise((resolve, reject) => {
dbInstance.update(collectionName, { id: 'item1' }, { value: updatedValue }, (err, data) => {
if (err) return reject(err); resolve(data);
});
});
console.log('Updated:', updateResult);
assert.strictEqual(updateResult.value, updatedValue, 'Document updated successfully');
// List all documents (simple read without query)
console.log('Listing all documents...');
const listResult = await new Promise((resolve, reject) => {
dbInstance.list(collectionName, (err, data) => {
if (err) return reject(err); resolve(data);
});
});
console.log('Listed:', listResult);
assert(Array.isArray(listResult), 'List should return an array');
// Delete a document
console.log('Deleting document...');
const deleteResult = await new Promise((resolve, reject) => {
dbInstance.delete(collectionName, { id: 'item1' }, (err, data) => {
if (err) return reject(err); resolve(data);
});
});
console.log('Deleted:', deleteResult);
assert.strictEqual(deleteResult.id, 'item1', 'Document deleted successfully');
// Verify deletion
const verifyDeletion = await new Promise((resolve, reject) => {
dbInstance.read(collectionName, { id: 'item1' }, (err, data) => {
if (err) return reject(err); resolve(data);
});
});
assert.strictEqual(verifyDeletion.length, 0, 'Document should no longer exist');
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
// fh-db itself doesn't expose a direct close method; it relies on the underlying MongoDB driver's connection pooling.
console.log('Example finished. Ensure your MongoDB connection is managed appropriately by the underlying driver.');
}
}
runExample();
Debug
Known issues
breakingWhen 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.fixBefore 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']})`. affects: All versions of `fh-db` when used with MongoDB Server >= 3.0.0.
gotcha`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()`).fixAlways 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. affects: All versions when attempting ESM imports in newer Node.js environments.
deprecatedThe `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.fixCheck `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.
affects: 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.
Errors
Common errors & fixes
Authentication failed.
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).
fixVerify 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.
TypeError: fhdb.db is not a function
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.
fixEnsure 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`. MongoError: auth failed
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.
fixEnsure 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.
Audit
Dependencies
mongodbrequiredCore dependency for database interactions; `fh-db` acts as a wrapper around the native MongoDB driver.