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

document-operations.mddocs/

Document Operations

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

Capabilities

Document Insertion

Insert single documents or arrays of documents into the database with automatic ID generation and validation.

/**
 * 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);

Usage Examples:

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

// Insert single document
db.insert({ name: 'Alice', age: 25, email: 'alice@example.com' }, (err, newDoc) => {
  if (err) {
    console.error('Insert failed:', err);
    return;
  }
  console.log('Inserted document:', newDoc);
  // newDoc will have auto-generated _id: { _id: 'random_id', name: 'Alice', age: 25, email: 'alice@example.com' }
});

// Insert multiple documents
const users = [
  { name: 'Bob', age: 30, role: 'admin' },
  { name: 'Charlie', age: 28, role: 'user' },
  { name: 'Diana', age: 32, role: 'moderator' }
];

db.insert(users, (err, newDocs) => {
  if (err) {
    console.error('Batch insert failed:', err);
    return;
  }
  console.log('Inserted', newDocs.length, 'documents');
  newDocs.forEach(doc => console.log('- ', doc.name, 'with ID:', doc._id));
});

// Insert with custom _id
db.insert({ _id: 'user_001', name: 'Eve', status: 'active' }, (err, newDoc) => {
  if (!err) {
    console.log('Document with custom ID:', newDoc._id); // 'user_001'
  }
});

// Insert with timestamps (if timestampData: true)
const timestampDb = new Datastore({ 
  filename: './logs.db', 
  timestampData: true, 
  autoload: true 
});

timestampDb.insert({ message: 'System startup' }, (err, newDoc) => {
  if (!err) {
    console.log('Created at:', newDoc.createdAt);
    console.log('Updated at:', newDoc.updatedAt);
  }
});

Document Querying

Find documents using MongoDB-style queries with support for projections and cursor chaining.

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

/**
 * Find single document matching query
 * @param {object} query - MongoDB-style query object
 * @param {object} projection - Optional field projection object
 * @param {function} callback - Optional callback function (err, doc) => {}
 * @returns {Cursor} Cursor for chaining operations if no callback provided
 */
findOne(query, projection, callback);

/**
 * Count documents matching query
 * @param {object} query - MongoDB-style query object
 * @param {function} callback - Optional callback function (err, count) => {}
 * @returns {Cursor} Cursor for chaining operations if no callback provided
 */
count(query, callback);

Usage Examples:

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

// Find all documents
db.find({}, (err, docs) => {
  if (!err) {
    console.log('All documents:', docs);
  }
});

// Find with query conditions
db.find({ age: { $gte: 18 } }, (err, adults) => {
  if (!err) {
    console.log('Adult users:', adults);
  }
});

// Find with field projection
db.find({ role: 'admin' }, { name: 1, email: 1 }, (err, admins) => {
  if (!err) {
    // Returns only name, email, and _id fields
    console.log('Admin users (name/email only):', admins);
  }
});

// Find one document
db.findOne({ name: 'Alice' }, (err, user) => {
  if (!err && user) {
    console.log('Found Alice:', user);
  } else if (!user) {
    console.log('Alice not found');
  }
});

// Count documents
db.count({ status: 'active' }, (err, count) => {
  if (!err) {
    console.log('Active users count:', count);
  }
});

// Using cursor for chaining (no callback)
db.find({ age: { $gte: 18 } })
  .sort({ age: 1 })
  .skip(5)
  .limit(10)
  .exec((err, docs) => {
    if (!err) {
      console.log('Sorted adults (page 2):', docs);
    }
  });

// Complex query with multiple conditions
db.find({
  $and: [
    { age: { $gte: 25 } },
    { role: { $in: ['admin', 'moderator'] } },
    { status: 'active' }
  ]
}, (err, docs) => {
  if (!err) {
    console.log('Senior staff members:', docs);
  }
});

Document Updates

Update documents with MongoDB-style update operators and options for multi-document updates and upserts.

/**
 * Update documents matching query
 * @param {object} query - MongoDB-style query object to select documents
 * @param {object} update - Update operations or replacement document
 * @param {object} options - Update options
 * @param {function} callback - Callback function (err, numAffected, affectedDocuments, upsert) => {}
 */
update(query, update, options, callback);

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

Usage Examples:

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

// Update single document with $set operator
db.update(
  { name: 'Alice' }, 
  { $set: { age: 26, status: 'premium' } }, 
  {}, 
  (err, numReplaced) => {
    if (!err) {
      console.log('Updated', numReplaced, 'document(s)');
    }
  }
);

// Update multiple documents
db.update(
  { role: 'user' }, 
  { $set: { role: 'member' } }, 
  { multi: true }, 
  (err, numReplaced) => {
    if (!err) {
      console.log('Updated', numReplaced, 'users to members');
    }
  }
);

// Upsert (insert if not found)
db.update(
  { email: 'new@example.com' }, 
  { $set: { name: 'New User', email: 'new@example.com', status: 'pending' } }, 
  { upsert: true }, 
  (err, numReplaced, upsertedDoc) => {
    if (!err) {
      if (upsertedDoc) {
        console.log('Inserted new document:', upsertedDoc);
      } else {
        console.log('Updated existing document');
      }
    }
  }
);

// Update with return updated documents
db.update(
  { status: 'pending' }, 
  { $set: { status: 'active', activatedAt: new Date() } }, 
  { multi: true, returnUpdatedDocs: true }, 
  (err, numReplaced, updatedDocs) => {
    if (!err) {
      console.log('Activated', numReplaced, 'users');
      updatedDocs.forEach(doc => {
        console.log('- Activated:', doc.name);
      });
    }
  }
);

// Increment numeric field
db.update(
  { name: 'Alice' }, 
  { $inc: { loginCount: 1 } }, 
  {}, 
  (err, numReplaced) => {
    if (!err) {
      console.log('Incremented login count for Alice');
    }
  }
);

// Add to array
db.update(
  { name: 'Bob' }, 
  { $push: { tags: 'vip' } }, 
  {}, 
  (err, numReplaced) => {
    if (!err) {
      console.log('Added VIP tag to Bob');
    }
  }
);

// Replace entire document (no operators)
db.update(
  { _id: 'user_001' }, 
  { name: 'Updated User', email: 'updated@example.com', version: 2 }, 
  {}, 
  (err, numReplaced) => {
    if (!err) {
      console.log('Replaced document entirely');
    }
  }
);

Document Removal

Remove documents from the database with support for single or multiple document deletion.

/**
 * Remove documents matching query
 * @param {object} query - MongoDB-style query object to select documents
 * @param {object} options - Remove options
 * @param {function} callback - Callback function (err, numRemoved) => {}
 */
remove(query, options, callback);

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

Usage Examples:

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

// Remove single document
db.remove({ name: 'Alice' }, {}, (err, numRemoved) => {
  if (!err) {
    console.log('Removed', numRemoved, 'document(s)');
  }
});

// Remove multiple documents
db.remove(
  { status: 'inactive' }, 
  { multi: true }, 
  (err, numRemoved) => {
    if (!err) {
      console.log('Removed', numRemoved, 'inactive users');
    }
  }
);

// Remove documents matching complex query
db.remove(
  { 
    $and: [
      { lastLogin: { $lt: new Date('2023-01-01') } },
      { status: 'pending' }
    ]
  }, 
  { multi: true }, 
  (err, numRemoved) => {
    if (!err) {
      console.log('Cleaned up', numRemoved, 'old pending accounts');
    }
  }
);

// Remove all documents (clear database)
db.remove({}, { multi: true }, (err, numRemoved) => {
  if (!err) {
    console.log('Cleared database:', numRemoved, 'documents removed');
  }
});

// Conditional removal with age check
const oneYearAgo = new Date();
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);

db.remove(
  { 
    createdAt: { $lt: oneYearAgo },
    archived: true 
  }, 
  { multi: true }, 
  (err, numRemoved) => {
    if (!err) {
      console.log('Removed', numRemoved, 'archived documents older than 1 year');
    }
  }
);

Document Validation Rules

  • Documents must be valid JavaScript objects
  • Field names cannot start with $ (reserved for operators)
  • Field names cannot contain dots (.) as they're used for nested field access
  • The _id field is automatically generated if not provided
  • _id values must be unique within the collection
  • Maximum document size depends on available memory (no hard limit)
  • All data types supported by JSON are valid (string, number, boolean, array, object, null)

docs

cursor-operations.md

database-management.md

document-operations.md

index-management.md

index.md

query-system.md

tile.json