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 to false): as the name implies.
  • timestampData (optional, defaults to false): timestamp the insertion and last update of all documents, with the fields createdAt and updatedAt. User-specified values override automatic generation, usually useful for testing.
  • autoload (optional, defaults to false): if used, the database will automatically be loaded from the datafile upon creation (you don't need to call loadDatabase). 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 the loadDatabase. It takes one error 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 of afterSerialization. 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. Native localCompare will most of thetime be the right choice
  • nodeWebkitAppName (optional, DEPRECATED): if you are using NeDB from whithin a Node Webkit app, specify its name (the same one you use in the package.json) in this field and the filename 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 use require('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 loadDatabaseis 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.

  1. // Type 1: In-memory only datastore (no need to load the database)
  2. var Datastore = require('nedb')
  3. , db = new Datastore();
  4. // Type 2: Persistent datastore with manual loading
  5. var Datastore = require('nedb')
  6. , db = new Datastore({ filename: 'path/to/datafile' });
  7. db.loadDatabase(function (err) { // Callback is optional
  8. // Now commands will be executed
  9. });
  10. // Type 3: Persistent datastore with automatic loading
  11. var Datastore = require('nedb')
  12. , db = new Datastore({ filename: 'path/to/datafile', autoload: true });
  13. // You can issue commands right away
  14. // Type 4: Persistent datastore for a Node Webkit app called 'nwtest'
  15. // For example on Linux, the datafile will be ~/.config/nwtest/nedb-data/something.db
  16. var Datastore = require('nedb')
  17. , path = require('path')
  18. , db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'something.db') });
  19. // Of course you can create multiple datastores if you need several
  20. // collections. In this case it's usually a good idea to use autoload for all collections.
  21. db = {};
  22. db.users = new Datastore('path/to/users.db');
  23. db.robots = new Datastore('path/to/robots.db');
  24. // You need to load each database (here we do it asynchronously)
  25. db.users.loadDatabase();
  26. db.robots.loadDatabase();