or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cursor-operations.mddatabase-management.mddocument-operations.mdindex-management.mdindex.mdquery-system.md
tile.json

tessl/npm-nedb

File-based embedded JavaScript database that provides persistent or in-memory data storage with a MongoDB-like API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/nedb@1.8.x

To install, run

npx @tessl/cli install tessl/npm-nedb@1.8.0

index.mddocs/

NeDB (Node Embedded Database)

NeDB is a lightweight embedded JavaScript database that provides persistent or in-memory data storage for Node.js, Electron, and browser applications. It implements a subset of MongoDB's API with 100% JavaScript implementation and no binary dependencies, making it ideal for applications requiring a simple database solution without server overhead.

Package Information

  • Package Name: nedb
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install nedb

Core Imports

const Datastore = require('nedb');

For ES modules:

import Datastore from 'nedb';

Basic Usage

const Datastore = require('nedb');

// Create in-memory database
const db = new Datastore();

// Create persistent database
const persistentDb = new Datastore({ filename: './data.db', autoload: true });

// Insert documents
db.insert({ name: 'Alice', age: 25 }, (err, newDoc) => {
  console.log('Inserted:', newDoc);
});

// Find documents
db.find({ age: { $gte: 18 } }, (err, docs) => {
  console.log('Adults:', docs);
});

// Update documents
db.update({ name: 'Alice' }, { $set: { age: 26 } }, {}, (err, numReplaced) => {
  console.log('Updated:', numReplaced);
});

// Remove documents
db.remove({ age: { $lt: 18 } }, { multi: true }, (err, numRemoved) => {
  console.log('Removed:', numRemoved);
});

Architecture

NeDB is built around several key components:

  • Datastore Class: Main database interface providing CRUD operations with MongoDB-like API
  • Cursor System: Chainable query interface for sorting, limiting, and pagination
  • Index Management: Automatic and custom indexing for query performance optimization
  • Persistence Layer: Crash-safe file operations with optional compression and encryption hooks
  • Query Engine: MongoDB-compatible query operators and update modifiers
  • Event System: EventEmitter-based notifications for database operations

Capabilities

Database Creation & Management

Core database initialization, loading, and lifecycle management including persistence options and configuration.

/**
 * Creates a new NeDB database instance
 * @param {string|object} options - Database configuration
 */
constructor Datastore(options);

Database Management

Document Operations

Complete CRUD operations for managing documents including insertion, querying, updating, and deletion with MongoDB-style syntax.

/**
 * Insert document(s) into database
 * @param {object|array} doc - Document or array of documents to insert
 * @param {function} callback - Callback function (err, insertedDoc) => {}
 */
insert(doc, callback);

/**
 * Find documents matching query
 * @param {object} query - MongoDB-style query object
 * @param {object} projection - Optional field projection
 * @param {function} callback - Callback function (err, docs) => {}
 * @returns {Cursor} Cursor for chaining if no callback provided
 */
find(query, projection, callback);

Document Operations

Query System

Advanced querying capabilities with MongoDB-compatible operators for complex data retrieval and filtering.

/**
 * MongoDB-style query operators
 */
interface QueryOperators {
  $lt: any;    // Less than
  $lte: any;   // Less than or equal
  $gt: any;    // Greater than
  $gte: any;   // Greater than or equal
  $ne: any;    // Not equal
  $in: any[];  // Value in array
  $nin: any[]; // Value not in array
  $regex: RegExp; // Regular expression match
  $exists: boolean; // Field exists check
  $size: number;    // Array size
  $elemMatch: object; // Element match in array
  $or: object[];   // Logical OR
  $and: object[];  // Logical AND
  $not: object;    // Logical NOT
  $where: function; // Function evaluation
}

Query System

Index Management

Performance optimization through automatic and custom indexing including unique constraints and TTL (time-to-live) indexes.

/**
 * Create or ensure index exists
 * @param {object} options - Index configuration
 * @param {function} callback - Callback function (err) => {}
 */
ensureIndex(options, callback);

Index Management

Cursor Operations

Chainable query interface for sorting, pagination, projection, and result processing with lazy evaluation.

/**
 * Cursor interface for chaining query operations
 */
interface Cursor {
  limit(limit: number): Cursor;
  skip(skip: number): Cursor;
  sort(sortQuery: object): Cursor;
  projection(projection: object): Cursor;
  exec(callback: function): void;
}

Cursor Operations

Types

/**
 * Database configuration options
 */
interface DatastoreOptions {
  filename?: string;                    // Path to database file
  inMemoryOnly?: boolean;              // Use memory-only storage (default: false)
  autoload?: boolean;                  // Auto-load database on creation (default: false)
  timestampData?: boolean;             // Auto-add createdAt/updatedAt (default: false)
  onload?: (err: Error) => void;       // Callback after autoload
  afterSerialization?: (data: string) => string;     // Transform before disk write
  beforeDeserialization?: (data: string) => string;  // Transform after disk read
  corruptAlertThreshold?: number;      // Corruption tolerance 0-1 (default: 0.1)
  compareStrings?: (a: string, b: string) => number; // Custom string comparison
}

/**
 * Index configuration options
 */
interface IndexOptions {
  fieldName: string;           // Field to index (required)
  unique?: boolean;           // Unique constraint (default: false)
  sparse?: boolean;           // Sparse index (default: false)
  expireAfterSeconds?: number; // TTL in seconds for automatic expiration
}

/**
 * Update operation options
 */
interface UpdateOptions {
  multi?: boolean;            // Update multiple documents (default: false)
  upsert?: boolean;          // Insert if no match found (default: false)
  returnUpdatedDocs?: boolean; // Return updated documents (default: false)
}

/**
 * Remove operation options
 */
interface RemoveOptions {
  multi?: boolean; // Remove multiple documents (default: false)
}