JavaScript
Article

How to Use RethinkDB with Node.js Applications

By Jay Raj

This article was peer reviewed by Agbonghama Collins and Martín Martínez. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

One of the most common task for a web application is to save data. Without the ability to store data, users would not be able to customize their preferences for an application, organize their data, or achieve similar tasks.
For a long time, the web has relied on relational database to save information. For example, on the web the liason between PHP and MySQL is well known. But not all the database must be relation!
In this article we’ll focus on using RethinkDB, an open source JSON database, with Node.js applications. We’ll make use of the RethinkDB Node.js driver called rethinkdbdash to connect to the database.

But before starting, let’s have a look at what RethinkDB is and where we might want to use it.

Introducing RethinkDB

RethinkDB is an open source JSON database built for real time Web.

The official documentation states:

RethinkDB is the first open-source, scalable JSON database built from the ground up for the realtime web. It inverts the traditional database architecture by exposing an exciting new access model – instead of polling for changes, the developer can tell RethinkDB to continuously push updated query results to applications in realtime.

It provides the functionality to get real time updates from the database each time a change occurs.

RethinkDB targets applications which require to send real time updates to the connected clients. For example, let’s consider an application that enables users to collaboratively design a plan. When a particular user makes a design change, it needs to be pushed to the other connected clients in real time to keep the design in sync. RethinkDB can be used in such cases to make real time updates possible.

Having clarified what RethinkDB could be useful for, let’s seen now how to install it.

Installing Rethinkdb

To install RethinkDB on Ubuntu, you need to add the repository.

source /etc/lsb-release && echo "deb http://download.rethinkdb.com/apt $DISTRIB_CODENAME main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list
wget -qO- http://download.rethinkdb.com/apt/pubkey.gpg | sudo apt-key add -

Then, you have to update the package information from the newly added repository and install RethinkDB.

sudo apt-get update
sudo apt-get install rethinkdb

For other OS flavors, you can follow the official installation instructions.

Once you are done, type on your terminal the following command:

rethinkdb

If everything is installed correctly, RethinkDB should start and it should run on the default port 28015. The administration console should be accessible at http://localhost:8080.

Installing the Node.js Client Rethinkdbdash

In the introduction of this tutorial, I have mentioned rethinkdbdash, the Node.js client we’ll use for interacting with the RethinkDB server. It is an advanced Node.js driver for RethinkDB with a connection pool, support for streams, etc.

To install the rethinkdbdash client, you can use npm:

npm install rethinkdbdash

Getting Started with RethinkDB

We’ll start by creating a database called SitePoint for our demo app. As the first step, create a project folder called NodeRethinkDB. Then, create a file called app.js inside the project directory.

Once done, import the client module in the app.js file as shown below:

var r = require('rethinkdbdash')();

The above statement connects to the default port address 28015 and hosts localhost. In case you need a different configuration, you can set it as follows:

var r = require('rethinkdbdash')({
	port: 28015,
	host: 'localhost'
});

Creating a Database

With the previous statement in place, we can create a database. This is done by using the dbCreate method.

r.dbCreate('SitePoint')
.run()
.then(function(response){
	console.log(response);
})
.error(function(err){
	console.log('error occured ', err);
});

If everything went fine, you should get a successful response as the one below.

{
  config_changes: [ { new_val: [Object], old_val: null } ],
  dbs_created: 1
}

If you take a look at the RethinkDB administration console running at port 8080, you should be able to see the newly created SitePoint database.

rethink_site

Creating a Table

Now we’ll see how to create a table in a RethinkDB database, using the rethinkdbdash client.
First, set up a connection to the database using the client.

var r = require('rethinkdbdash')({
	port: 28015,
	host: 'localhost',
	db: 'SitePoint'
});

Now, we’ll make use of the tableCreate method to create a table Employee in the database.

r.tableCreate('Employee')
.run()
.then(function(response){
	console.log(response);
})
.error(function(err){
	console.log('error while creating table ', err);
})

By default, the primary key is id. If you want, you can specify it while creating the table.

r.tableCreate('Employee',{ primaryKey: 'name' })
.run()
.then(function(response){
	console.log(response)
})
.error(function(err){
	console.log('error while creating table ',err)
})

The above query returns the following response:

Creating a pool connected to localhost:28015

{
  config_changes: [ { new_val: [Object], old_val: null } ],
  tables_created: 1
}

Inserting Data

To insert data into the Employee table, we’ll make use of the insert method.

r.table("Employee")
.insert({
    name: "Jay",
    company: "SitePoint"
})
.run()
.then(function(response){
	console.log('Success ',response);
})
.error(function(err){
	console.log('error occurred ',err);
})

The code above insert the data into the Employee table and return the successful message. Here is the response from the query above:

Creating a pool connected to localhost:28015

Success

{
  deleted: 0,
  errors: 0,
  generated_keys: [ 'f64a2bdb-1659-47a9-9bc1-89e8f1ebb2ac' ],
  inserted: 1,
  replaced: 0,
  skipped: 0,
  unchanged: 0
}

One thing worth noting in the insert query is that we haven’t specified the id field. If we prefer, we can do it. Otherwise, it will have an autogenerated unique identifier value.

Selecting Data from Table

Selecting data from the table is quite straightforward. We need to specify the name of the table and the data gets selected.

r.table('Employee')
.run()
.then(function(response){
	console.log(response);
})
.error(function(err){
	console.log(err);
})

The snippet above gives the following output:

[{
    EmpId: 'bc95940f-084c-48c5-b9fe-dc0a82f380b6',
    name: 'Jay',
    company: 'SitePoint'
}]

Selecting Specific Records from Table

We employ the get method to get records with a particular primary key. For example, if we want to select an Employee with an EmpId of bc95940f-084c-48c5-b9fe-dc0a82f380b6, this is the query we must run:

r.table('Employee')
.get('bc95940f-084c-48c5-b9fe-dc0a82f380b6')
.run()
.then(function(response){
	console.log(response);
})
.error(function(err){
	console.log(err);
})

The above query would return the details of the Employee with ID bc95940f-084c-48c5-b9fe-dc0a82f380b6 as reported below:

[{
    EmpId: 'bc95940f-084c-48c5-b9fe-dc0a82f380b6',
    name: 'Jay',
    company: 'SitePoint'
}]

Pushing Update in Real Time

One of the most important features of the RethinkDB is its ability to push changes in real time, which reduces the polling overhead. From the official docs you can read:

Instead of polling for changes, the developer can tell RethinkDB to continuously push updated query results in realtime.

Pushing updates can be achieved by subscribing to the realtime feeds. For example, we can subscribe for any changes in the Employee table as shown below:

r.table('Employee')
.changes()
.run()
.then(function(cursor){
	cursor.each(console.log);
})
.error(function(err){
	console.log(err);
});

Now, when inserting a record into Employee, in the terminal we’ll see a log as the following:

{
  new_val: {
     EmpId: '57937293-850b-45af-aeb3-e30d2dfd83a2',
     company: 'SitePoint',
     name: 'Raj'
  },
  old_val: null
}

The above log is for an insert statement, hence the old_val is null and new_val has value. In case an existing record gets updated, we will have both the old_val and the new_val.

Conclusions

In this tutorial, we’ve seen how to use RethinkDB with Node.js applications thanks to the RethinkDB Node.js driver called rethinkdbdash.
If you want to deepen the topic, I suggest you to take a look at the official documentation and at the Rethink Db JavaScript command reference.
Have you ever used any other client for connecting to RethinkDB from Node.js?
Share your thoughts and suggestions in the comments below!

  • Igor Khomenko

    Is it possible to use filters for changes() ?

    For example,

    r.table(‘Employee’)
    .changes(“age > 20”)
    .run()

    • AureliusCorp

      Don’t can, because you only have the possibility to pass some parameters on an object as: (squash,includeStates,includeInitial,changefeedQueueSize) then this should be done in the callback.

      • Suzanne Lewis

        I am getting a salary of more than 3900 dollars each week , that is awesome. Over a year ago I was in a horrible condition , jobless and Bank account with only few bucks . Thank one of my friends showed me a way where I was able to gather my self and making average of 85 d/h. So it can change your life as it has changed mine.

        coolmath.CO.NF

        uio…

    • You can put a filter before the changes command and it will give you a changefeed on the filtered subset:

      r.table(“Employee”).filter(r.row(“age”).gt(20)).changes().run()

  • Great article Jay!

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.