FeedHenry Database Library
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.
Common errors
-
Authentication failed.
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).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
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.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
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.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.
Warnings
- breaking 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.
- 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()`).
- deprecated 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.
Install
-
npm install fh-db -
yarn add fh-db -
pnpm add fh-db
Imports
- fhdb
import fhdb from 'fh-db';
const fhdb = require('fh-db'); - dbInstance
const dbInstance = fhdb.db(process.env.MONGO_URI || 'mongodb://localhost:27017/mydatabase');
- CRUD operations
dbInstance.create('mycollection', { name: 'test' }, (err, data) => {});
Quickstart
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();