
NeDB (
N ode.js
E mbedded
D ata
b ase) is an embedded database for NodeJS that implements a subset of the MongoDB API. This light NoSQL DBMS is written in pure JavaScript, has no binary dependencies and, in addition to NodeJS, can be used in NW.js, Electron or directly in the browser.
NeDB provides data storage in a simple file on a disk in a json-format which is similar to collections in MongoDB.
Installation
NeDB is available from bower and npm:
npm install nedb --save
Let's create a data store called "users":
var Datastore = require('nedb'); var db = new Datastore({filename : 'users'}); db.loadDatabase();
This will create a file called users in your working directory. If you want to use NeDB for storage in memory, you need to use a constructor without parameters, i.e. do not pass it the file name.
')
CRUD
Let's insert the entry:
db.insert({name : "Boris the Blade", year: 1946});
Open the users file to see the inserted object. NeDB automatically adds the "_id" field for each object. To insert more than one entry, pass an array to the insert method. Such an operation is atomic, so if one of the inserts fails, the other will be rolled back.
Extract data:
db.find({year: 1946}, function (err, docs) { console.log(docs); });
This method accepts a request as an object and a callback function; docs is an array containing the search results. In this example, we simply output this array to the console.
Update data:
To update the data you need to pass three arguments:
- request to search for the document to be changed;
- object to replace;
- replacement parameters (we will leave them empty - {}).
db.update({year: 1946}, {name: "Doug the Head", year: 1940}, {});
Run the query and look at the users file. See something unusual? The first entry (Boris Razor) is still in the file. This is due to the mechanics of NeDB, which believes that it is not worth wasting time rewriting records. NeDB just adds new lines. The same applies to the delete operation:
db.remove({year: 1946}, {});
Indexing
NeDB supports indexes almost like in Mongo:
db.ensureIndex({fieldName: 'year'});
This allows you to speed up the search for data in the year field. You can index any fields, including fields in attached documents.
Speed
NeDB is not intended to replace large-scale databases such as MongoDB. However, the database works fairly quickly on the expected data sets, especially after indexing. The documentation states that “on a regular, not-very-fast dev machine” for a collection of 10,000 NeDB documents shows:
Insert: 10,680 ops / s
Search: 43,290 ops / s
Update: 8,000 ops / s
Removal: 11,750 ops / s
Slightly more accurate benchmarking benchmarks for
NeDB versus MongoDB, Tingodb and EJDB .
That's all. You just met NeDB.