Use Cloudant DB in IBM Bluemix to Store Sensor Values

Cloudant Database

In the previous tutorial you learnt how to use Node-RED editor to make IoT apps in IBM Bluemix. In this short tutorial I will show you how to use Cloudant database to store sensor values that come from your devices. As you have seen, when you create a new app, a Cloudant DB service is automatically bound to it. In the Node-RED flow editor, there are two Cloudant nodes, Cloudant in for searching databases and Cloudant out for storing data.

From the main dashboard, go to Cloudant service and launch the dashboard. Click Create Database and give it a name.

List of all databases

Right now, it is empty. To start entering data, go to Node-RED editor and connect IoT input node to the Cloudant out node. Put a function node between these two. Your flow should look like this:


Configure Cloudant node, specify database name you want to write to, and check the box.

Edit Cloudant out node

For this demonstration, we will send temperature and humidity values form the ESP8266. Payload should look like this:

{ "d": { 
           "Name": "18FE34D81E46", 
           "temperature": 25, 
            "humidity": 40 
} }

If you don't have temperature and humidity sensors, you can use some others, set a counter or generate random numbers to simulate humidity and temperature values:

 String payload = "{\"d\":{\"Name\":\"18FE34D81E46\"";
 payload += ",\"temperature\":";
 payload += temperature;
 payload += ",\"humidity\":";
 payload += humidity;
 payload += "}}";

Since Cloudant out node stores msg.payload, in order to store each parameter separately, in the function node put this code:

msg.payload = msg.payload.d;
return msg;

When your device starts publishing sensor values, you should see these records in database.

Database with new records

If you don’t specify ID for a record, it will be randomly generated. There is also possibility to update and delete existing records. You can use Cloudant in node to query databases from Node-RED editor.

If you want to add a date and time as a new column in the database, you can modify your function node like this:

msg.payload = msg.payload.d;
var date = new Date(); = date;
return msg;

Database with date column

That’s it, a very simple way to store data that comes from your devices.

Lessons of this Series

Online computer science courses to jumpstart your future.
WP Engine Managed WordPress Hosting


