NeDB Deployment & Usage Guide
⚠️ Security Warning: This library is no longer maintained and may contain bugs or security vulnerabilities. Use only in legacy systems or fork for maintenance. No pull requests or security alerts will be answered by the original maintainers.
1. Prerequisites
- Node.js (v0.10 or higher) and npm
- File system permissions: Read/write access to the directory where persistent datafiles will be stored
- For browser/Electron/NW.js usage: Modern JavaScript environment with ES5 support
- For development/testing: Git
2. Installation
In a Node.js/Electron/NW.js Project
npm install nedb --save
For Browser Usage (Legacy)
bower install nedb
Browser-compatible files will be located in browser-version/out/.
Development/Fork Setup
git clone https://github.com/louischatriot/nedb.git
cd nedb
npm install # Installs dev dependencies required for testing
npm test # Runs the test suite
3. Configuration
NeDB is configured via the Datastore constructor options:
const Datastore = require('nedb');
const db = new Datastore({
filename: './data/mydatabase.db', // Optional: omit for in-memory only
inMemoryOnly: false, // Default: false
autoload: true, // Auto-load on instantiation
timestampData: false, // Auto-add createdAt/updatedAt
corruptAlertThreshold: 0.1, // 10% corruption tolerance (0-1)
// Optional: Custom string comparison for sorting non-US characters
compareStrings: function(a, b) { return a.localeCompare(b); },
// Optional: Encryption hooks (must provide both or neither)
afterSerialization: function(string) { return encrypted(string); },
beforeDeserialization: function(string) { return decrypted(string); },
// Optional: Callback for autoload errors
onload: function(err) { if (err) console.error('Load error:', err); }
});
Critical Constraints
- Field names cannot begin with
$(reserved for operators) or contain.(reserved for dot notation) - Filename cannot end with
~(reserved for crash-safe backup files) - Serialization hooks: If
afterSerializationis defined,beforeDeserializationmust also be defined, and they must be exact inverses
4. Build & Run
Running Tests
npm test
Requires dev dependencies installed.
Basic Usage Example
const Datastore = require('nedb');
const path = require('path');
// Persistent database
const db = new Datastore({ filename: path.join(__dirname, 'data.db'), autoload: true });
// Or in-memory only
// const db = new Datastore();
// Insert
db.insert({ name: 'John', age: 30 }, function(err, newDoc) {
if (err) throw err;
console.log('Inserted:', newDoc);
});
// Find with MongoDB-like syntax
db.find({ age: { $gte: 25 } }).sort({ name: 1 }).exec(function(err, docs) {
console.log(docs);
});
// Update
db.update({ name: 'John' }, { $set: { age: 31 } }, {}, function(err, numReplaced) {
console.log('Updated', numReplaced, 'document(s)');
});
// Remove
db.remove({ name: 'John' }, {}, function(err, numRemoved) {
console.log('Removed', numRemoved, 'document(s)');
});
Manual Loading (if not using autoload)
const db = new Datastore({ filename: './data.db' });
db.loadDatabase(function(err) {
if (err) throw err;
// Database ready for commands
});
5. Deployment
Node.js Server Deployment
- File Permissions: Ensure the Node.js process has read/write access to the directory containing the
.dbfile - Docker: Mount a volume for the data directory to persist data between container restarts:
VOLUME ["/app/data"] - Backup: Copy the
.dbfile while the application is running (NeDB uses append-only writes, making hot backups safe)
Electron/NW.js Desktop Apps
- Data Path: Use the application's data directory instead of relative paths:
// Electron const { app } = require('electron'); const dbPath = path.join(app.getPath('userData'), 'myapp.db'); // NW.js (deprecated option no longer recommended) const dbPath = path.join(require('nw.gui').App.dataPath, 'myapp.db'); - Packaging: Include the
data.dbfile in your build if shipping with seed data
Browser Deployment
Include the built library from browser-version/out/:
<script src="path/to/nedb.min.js"></script>
<script>
var db = new Nedb({ filename: 'mydb', inMemoryOnly: true }); // Browser uses in-memory only
</script>
Indexing for Production
Create indexes for frequently queried fields to improve performance:
db.ensureIndex({ fieldName: 'email', unique: true, sparse: true }, function(err) {
if (err) console.error('Index creation failed:', err);
});
6. Troubleshooting
"Field names cannot begin with the $ character"
Cause: Document keys starting with $ (e.g., { $price: 100 })
Solution: Rename fields. $ is reserved for query operators (like $gt, $in). Exception: Internal fields like $$date are handled automatically.
"Field names cannot contain a ."
Cause: Document keys containing dots (e.g., { "user.name": "John" })
Solution: Use nested objects instead: { user: { name: "John" } }
"The datafile name can't end with a ~"
Cause: Filename ending with ~ (e.g., data.db~)
Solution: Remove the trailing ~. This suffix is reserved for NeDB's crash-safe backup files.
"Serialization hook defined but deserialization hook undefined"
Cause: Only one of afterSerialization or beforeDeserialization was provided
Solution: Provide both functions or neither. They must be perfect inverses of each other.
Database refuses to start (corruption alert)
Cause: More than corruptAlertThreshold (default 10%) of datafile lines are corrupted
Solution:
- Check that serialization/deserialization hooks match (if previously used)
- Restore from backup
- Increase
corruptAlertThreshold(not recommended for production)
Commands not executing (persistent mode)
Cause: Forgot to call loadDatabase() when not using autoload: true
Solution: Add autoload: true to options or manually call db.loadDatabase(callback) before issuing commands.
Data not persisting
Cause: Using in-memory mode unintentionally or process exiting before writes complete
Solution:
- Ensure
filenameis specified andinMemoryOnlyis nottrue - For graceful shutdown, allow pending operations to complete before process exit (NeDB writes are asynchronous)