MongoDB Abstract-Level Database
mongodb-level is an implementation of the `abstract-level` interface, providing a LevelDB-like key-value store API that is backed by a MongoDB database. This allows developers to interact with MongoDB using familiar operations such as `put`, `get`, `del`, and `iterator`, abstracting away the direct MongoDB Node.js driver API. Currently at version 0.0.4, the library is in an early, pre-stable development phase, indicating that its API may evolve. Given its early stage and specific niche, the release cadence is likely slow and focused on stability. Its key differentiator lies in offering a standardized LevelDB API over MongoDB, which can be advantageous for projects migrating from other LevelDB implementations or those aiming to standardize their data access layer across different storage backends.
Common errors
-
MongooseServerSelectionError: connect ECONNREFUSED <your-mongodb-host>:<port>
cause The MongoDB server is not running or is inaccessible from the application's host and port.fixVerify your MongoDB server is running and accessible. Check the `MONGODB_URI` connection string for correct host, port, and credentials. Ensure no firewall is blocking the connection. -
NotFoundError: Key 'someKey' not found
cause An attempt was made to retrieve a key that does not exist in the database.fixThis is expected behavior for `abstract-level` when a key is not found. Catch the error using a `try...catch` block and check `error.code === 'LEVEL_NOT_FOUND'` to handle it gracefully. -
TypeError: MongoDBLevel is not a constructor
cause Attempting to instantiate `MongoDBLevel` after using a CommonJS `require()` statement instead of an ESM `import` statement for a module that is ESM-only or transpiled.fixEnsure you are using `import { MongoDBLevel } from 'mongodb-level';` and that your project is configured for ES Modules (e.g., by adding `"type": "module"` to your `package.json` or using `.mjs` file extension).
Warnings
- gotcha The package is currently at version 0.0.4, indicating it is in a very early, pre-stable development stage. The API is subject to change without adhering to semantic versioning until a 1.0 release.
- gotcha As with any `abstract-level` implementation, operations are inherently asynchronous. Mixing synchronous calls or incorrect Promise handling can lead to unexpected behavior or unhandled rejections.
- gotcha Performance characteristics of `mongodb-level` are ultimately tied to the underlying MongoDB performance. Neglecting proper MongoDB indexing or schema design can lead to slow queries, even when using the `abstract-level` API.
- gotcha The `db.open()` and `db.close()` methods should be called to manage the database connection lifecycle. Failing to close the database can leave open connections, preventing your Node.js process from exiting gracefully.
Install
-
npm install mongodb-level -
yarn add mongodb-level -
pnpm add mongodb-level
Imports
- MongoDBLevel
const MongoDBLevel = require('mongodb-level')import { MongoDBLevel } from 'mongodb-level' - AbstractLevel
import type { AbstractLevel } from 'abstract-level' - MongoClient
import { MongoClient } from 'mongodb'
Quickstart
import { MongoDBLevel } from 'mongodb-level';
import { MongoClient } from 'mongodb';
const MONGODB_URI = process.env.MONGODB_URI ?? 'mongodb://localhost:27017';
const DB_NAME = process.env.DB_NAME ?? 'test_level_db';
const COLLECTION_NAME = process.env.COLLECTION_NAME ?? 'level_collection';
async function run() {
let client: MongoClient | undefined;
let db: MongoDBLevel | undefined;
try {
client = await MongoClient.connect(MONGODB_URI);
console.log('Connected to MongoDB.');
db = new MongoDBLevel({
dbName: DB_NAME,
collectionName: COLLECTION_NAME,
mongoClient: client
});
await db.open();
console.log('MongoDBLevel opened.');
// 1. Put a key-value pair
await db.put('hello', 'world');
console.log("Put 'hello': 'world'");
// 2. Get the value for a key
const value = await db.get('hello');
console.log(`Get 'hello': ${value}`); // Expected: world
// 3. Try to get a non-existent key
try {
await db.get('nonExistentKey');
} catch (error: any) {
if (error.code === 'LEVEL_NOT_FOUND') {
console.log('Successfully caught NotFoundError for nonExistentKey.');
} else {
throw error;
}
}
// 4. Delete a key
await db.del('hello');
console.log("Deleted 'hello'");
// 5. Verify deletion
try {
await db.get('hello');
} catch (error: any) {
if (error.code === 'LEVEL_NOT_FOUND') {
console.log("Successfully verified 'hello' is deleted.");
} else {
throw error;
}
}
} catch (err) {
console.error('An error occurred:', err);
} finally {
if (db) await db.close();
if (client) await client.close();
console.log('Database and MongoDB client closed.');
}
}
run();