CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nedb

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

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

database-management.mddocs/

Database Management

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

Capabilities

Database Constructor

Creates a new NeDB database instance with configurable persistence, indexing, and data processing options.

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

/**
 * Constructor options for database configuration
 */
interface DatastoreOptions {
  filename?: string;                    // Path to database file (null for in-memory)
  inMemoryOnly?: boolean;              // Force memory-only storage (default: false)
  autoload?: boolean;                  // Automatically load database on creation (default: false)
  timestampData?: boolean;             // Add createdAt/updatedAt timestamps (default: false)
  onload?: (err: Error) => void;       // Callback executed after autoload
  afterSerialization?: (data: string) => string;     // Transform data before disk write
  beforeDeserialization?: (data: string) => string;  // Transform data after disk read
  corruptAlertThreshold?: number;      // Corruption tolerance threshold 0-1 (default: 0.1)
  compareStrings?: (a: string, b: string) => number; // Custom string comparison function
  nodeWebkitAppName?: string;          // NW.js app name for relative paths (deprecated)
}

Usage Examples:

const Datastore = require('nedb');

// In-memory database
const memoryDb = new Datastore();

// Persistent database with autoload
const db = new Datastore({ 
  filename: './data/users.db', 
  autoload: true 
});

// Database with timestamps and custom serialization
const timestampDb = new Datastore({
  filename: './data/logs.db',
  timestampData: true,
  afterSerialization: (data) => {
    // Compress data before writing
    return compress(data);
  },
  beforeDeserialization: (data) => {
    // Decompress data after reading
    return decompress(data);
  }
});

// Legacy constructor (v0.6 compatibility)
const legacyDb = new Datastore('./data/legacy.db');

Database Loading

Explicitly load database from persistent storage, triggering execution of any buffered commands.

/**
 * Load database from datafile and execute buffered commands
 * @param {function} callback - Optional callback function (err) => {}
 */
loadDatabase(callback);

Usage Examples:

const db = new Datastore({ filename: './data.db' });

// Load database with callback
db.loadDatabase((err) => {
  if (err) {
    console.error('Failed to load database:', err);
    return;
  }
  console.log('Database loaded successfully');
  
  // Database is now ready for operations
  db.insert({ message: 'Hello World' }, (err, doc) => {
    if (!err) console.log('Document inserted:', doc);
  });
});

// Load database without callback (errors will be thrown)
db.loadDatabase();

Database Properties

Access database configuration and internal state through instance properties.

/**
 * Database instance properties
 */
interface DatastoreProperties {
  filename: string | null;        // Database file path (null for in-memory)
  inMemoryOnly: boolean;         // Memory-only storage flag
  autoload: boolean;             // Autoload configuration flag
  timestampData: boolean;        // Timestamp configuration flag
  compareStrings: function;      // Custom string comparison function
  persistence: Persistence;      // Persistence handler instance
  executor: Executor;           // Command executor instance
  indexes: object;              // Field name to Index mapping
  ttlIndexes: object;           // TTL index configurations
}

Usage Examples:

const db = new Datastore({ 
  filename: './data.db', 
  timestampData: true 
});

console.log('Database file:', db.filename);        // './data.db'
console.log('In memory only:', db.inMemoryOnly);   // false
console.log('Timestamps enabled:', db.timestampData); // true
console.log('Available indexes:', Object.keys(db.indexes)); // ['_id', ...]

Database Compaction

Manual and automatic database compaction to optimize storage and remove deleted documents.

/**
 * Manually trigger database compaction
 */
persistence.compactDatafile();

/**
 * Set automatic compaction interval
 * @param {number} interval - Milliseconds between compactions (minimum 5000)
 */
persistence.setAutocompactionInterval(interval);

/**
 * Stop automatic compaction
 */
persistence.stopAutocompaction();

Usage Examples:

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

// Manual compaction
db.persistence.compactDatafile();

// Automatic compaction every 30 seconds
db.persistence.setAutocompactionInterval(30000);

// Stop automatic compaction
db.persistence.stopAutocompaction();

// Listen for compaction events
db.on('compaction.done', () => {
  console.log('Database compaction completed');
});

Event Handling

Database events for monitoring compaction and other operations.

/**
 * Database events (extends EventEmitter)
 */
interface DatastoreEvents {
  'compaction.done': () => void; // Fired when compaction operation completes
}

Usage Examples:

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

// Listen for compaction completion
db.on('compaction.done', () => {
  console.log('Database has been compacted');
  console.log('File size optimized');
});

// Set up automatic compaction with event monitoring
db.persistence.setAutocompactionInterval(60000); // Every minute

db.on('compaction.done', () => {
  const stats = require('fs').statSync(db.filename);
  console.log('Current database size:', stats.size, 'bytes');
});

docs

cursor-operations.md

database-management.md

document-operations.md

index-management.md

index.md

query-system.md

tile.json