MongoDB Abstract-Level Database

0.0.4 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

Demonstrates basic `mongodb-level` operations (put, get, del) against a local or cloud MongoDB instance, including error handling for non-existent keys. It requires a MongoDB server to be running or a valid connection string to MongoDB Atlas.

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();

view raw JSON →