a blog for those who code

Sunday 11 September 2016

Getting to know more about RethinkDB in Nodejs

In this post we will be discussing about getting to know more about RethinkDB in Node.js. In our previous post we have discussed about Getting Started with RethinkDB in Nodejs. In this article we will be continuing our discussion on RethinkDB, which is an open-source database for the real-time web, and how it will help us to push data real time in our application.


Inserting Data Into Table


To insert data into the table in RethinkDB we will be using insert method.

rethinkDb.db('example').table('table1')
.insert({
  post: "1",
  title: "Coding Defined 1st Post"
})
.run().then(function(response){
  console.log(response);
}).error(function(err){
  console.log('Error ' + err);
});

The above query will return the following response


On thing to note here that you need not have to specify Id field which will be auto generated.  If you want to you can i.e. there is no hard and fast rule that you shouldn't specify Id field.

Selecting Data from Table


To select data from the table you just need to specify the name of the table and all the data will be selected for you as shown below

rethinkDb.db('example').table('table1')
.run().then(function(response){
  console.log(response);
}).error(function(err){
  console.log('Error ' + err);
});

The above query will return the following output


If you need to select a specific records then you can take the use of get method as shown below

rethinkDb.db('example').table('table1')
.get('5b063bd7-2770-416c-b5f4-74ac41b3e9f3')
.run().then(function(response){
  console.log(response);
}).error(function(err){
  console.log('Error ' + err);
});

Getting Real Time Data


RethinkDB is best suited when you have real time data coming in and you want that data to continuously refresh in your front end for the users to see. This can be achieved in RethinkDB by subscribing to the real-time feeds. For example if I need my table to continuously check for new values I will subscribe to it as shown below :

rethinkDb.db('example').table('table1')
.changes()
.run().then(function(cursor){
  cursor.each(console.log);
}).error(function(err){
  console.log('Error ' + err);
});

Which will be give the output as


You can also check the short video which shows how the select command is refreshed whenever a new data is inserted into the table in RethinkDB.


Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment