Creating/loading a database
You can use NeDB as an in-memory only datastore or as a persistent datastore. One datastore is the equivalent of a MongoDB collection. The constructor is used as follows new Datastore(options)
where options
is an object with the following fields:
filename
(optional): path to the file where the data is persisted. If left blank, the datastore is automatically considered in-memory only. It cannot end with a~
which is used in the temporary files NeDB uses to perform crash-safe writes.inMemoryOnly
(optional, defaults tofalse
): as the name implies.timestampData
(optional, defaults tofalse
): timestamp the insertion and last update of all documents, with the fieldscreatedAt
andupdatedAt
. User-specified values override automatic generation, usually useful for testing.autoload
(optional, defaults tofalse
): if used, the database will automatically be loaded from the datafile upon creation (you don't need to callloadDatabase
). Any command issued before load is finished is buffered and will be executed when load is done.onload
(optional): if you use autoloading, this is the handler called after theloadDatabase
. It takes oneerror
argument. If you use autoloading without specifying this handler, and an error happens during load, an error will be thrown.afterSerialization
(optional): hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing database to disk. This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a\n
character (or data will be lost).beforeDeserialization
(optional): inverse ofafterSerialization
. Make sure to include both and not just one or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below).corruptAlertThreshold
(optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care.compareStrings
(optional): function compareStrings(a, b) comparesstrings a and b and return -1, 0 or 1. If specified, it overridesdefault string comparison which is not well adapted to non-US charactersin particular accented letters. NativelocalCompare
will most of thetime be the right choicenodeWebkitAppName
(optional, DEPRECATED): if you are using NeDB from whithin a Node Webkit app, specify its name (the same one you use in thepackage.json
) in this field and thefilename
will be relative to the directory Node Webkit uses to store the rest of the application's data (local storage etc.). It works on Linux, OS X and Windows. Now that you can userequire('nw.gui').App.dataPath
in Node Webkit to get the path to the data directory for your application, you should not use this option anymore and it will be removed.
If you use a persistent datastore without the autoload
option, you need to call loadDatabase
manually.This function fetches the data from datafile and prepares the database. Don't forget it! If you use apersistent datastore, no command (insert, find, update, remove) will be executed before loadDatabase
is called, so make sure to call it yourself or use the autoload
option.
Also, if loadDatabase
fails, all commands registered to the executor afterwards will not be executed. They will be registered and executed, in sequence, only after a successful loadDatabase
.
// Type 1: In-memory only datastore (no need to load the database)
var Datastore = require('nedb')
, db = new Datastore();
// Type 2: Persistent datastore with manual loading
var Datastore = require('nedb')
, db = new Datastore({ filename: 'path/to/datafile' });
db.loadDatabase(function (err) { // Callback is optional
// Now commands will be executed
});
// Type 3: Persistent datastore with automatic loading
var Datastore = require('nedb')
, db = new Datastore({ filename: 'path/to/datafile', autoload: true });
// You can issue commands right away
// Type 4: Persistent datastore for a Node Webkit app called 'nwtest'
// For example on Linux, the datafile will be ~/.config/nwtest/nedb-data/something.db
var Datastore = require('nedb')
, path = require('path')
, db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'something.db') });
// Of course you can create multiple datastores if you need several
// collections. In this case it's usually a good idea to use autoload for all collections.
db = {};
db.users = new Datastore('path/to/users.db');
db.robots = new Datastore('path/to/robots.db');
// You need to load each database (here we do it asynchronously)
db.users.loadDatabase();
db.robots.loadDatabase();