NeDB basics

nedb-logoNeDB comes from Node.js Embedded Database. It is a lightweight NoSQL database written in pure JavaScript that can be used both as persistent and in-memory storage.

NeDB has a MongoDB-like syntax that supports CRUD-operations and indexing. It provides datastores that are similar to MongoDB collections. Datastore is a simple file on the disk which is used for carrying records in JSON-format.

Now we will go through NeDB basics. In this tutorial we will use this DB in the mode of persistent storage. Let’s switch to Node.js CLI and create a datastore called “guitars”:

> var Datastore = require('nedb'), db = new Datastore({filename : 'guitars'});
> db.loadDatabase();

It will create a file named “guitars” in your working directory. If you want to use NeDB as in-memory store you will need to use a constructor without parameters specified.

CRUD operations

Let’s insert a record:

> db.insert({name : "fender jazz bass", year:1977});

Open “guitars” file to see inserted object. NeDB adds “_id” field automatically for each inserted object. To insert more than one records pass an array into insert method. Such operation is atomic, so if one of insertions fails other one would be rolled back.

Retrieving data:

>db.find({year : 1977}, function (err,docs){ console.log(docs); });

This method accepts a query-object and a callback function; docs is an array that contains results of a query. In this case we will just print this array.

Updating data. You need to pass 3 arguments: query, replacement object, options object (we will leave it blank – {}):

> db.update({year : 1977}, {name : "gibson thunderbird", year: 1990}, {});

Please checkout your guitars file. Do you notice something special? Correct! First record (named fender jazz bass) is still in the file. This happens because of mechanics of NeDB. Since disk space is cheap it does not waste time on rewriting a record – it just adds another lines with “_id” of record that needs to be replaced. Same thing appears for deletions:

> db.remove ({year:1990}, {});

NeDB Indexing

NeDB supports indexes. Command is pretty much the same as in Mongo:

> db.ensureIndex({fieldName : 'year'});

This will speed up your storage a little bit when finding data by year field.

That’s all. You’ve just learned NeDB basics.

This DB was not created to replace powerful databases. It will fit with simple application that don’t need lots of concurrent connections.

Leave a Reply

Be the First to Comment!