Connecting to MongoDB service on bluemix using Node JS application and inserting data

In this blog,I will show you how to connect to Compose for MongoDB service on bluemix from our Node js application and then how to insert some data in to a collection.
First thing is that we need to create a new Compose for Mongo DB service On Bluemix.

mongodb.PNG

In the credentials you will have uri which is important and you need only that to connect from your node application

uri

Once you have  these you can start with your Node js application.
You require mongodb npm package to connect to this.So you need to import this module other than the default modules.
We need to use MongoClient constructor to connect to mongodb

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
var collectionName = "";
var options = {
  mongos: {
    ssl: true,
    sslValidate: false,
  }
}
var mongo=process.env.VCAP_SERVICES;
var port = process.env.PORT || 3030;
router.use(bodyParser.json());
var conn_str = "";
var mongoDbConn;

As I told earlier ,we need mongo uri to connect.We can directly hardcode that in our code or else we can bind a custom provided service(cups) to your bluemix application and access that value using VCAP_SERVICES.Second option is the best one as dont need any hardcoding.
So here we need to bind that service to our application on bluemix. In above code mongo is directly accessing that service. Now we need to capture the uri value from that and connect to mongo using the MongoClient which is done below

if (mongo) {
  var env = JSON.parse(mongo);
  if (env['user-provided']) {
    mongo = env['user-provided'][0]['credentials'];
    console.log(mongo);
    if (mongo.uri) {
      conn_str = mongo.uri;

      MongoClient.connect(conn_str, options, function (err, db) {
        if (err) {
          res.send("Mongo DB with conn ${conn_str} has error ${err}");
        } else {
          mongoDbConn = db;
        }
      });

    } else {
      console.log("No mongo found");
    }
  } else {
    console.log('No mongo found');
  }
} else {
  console.log('No mongo found');
}

You can also directly hardcode your value for mongo.uri value if required.
So once you have your mongo connection,you don’t need to connect every time when you need to add some data or insert anything using rest call .You just need to use mongoDbConn .
In below example I will show you a POST call which will insert data in to a collection using mongoDbConn

router.post('/insertnewevent', function (req, res) {
  var eventdetails = req.body;
  var data = { "customer": "harish", "transactionID":"3405123","transdate":"11/06/17"};
  
  var collectionName = "logdetails";

  if (mongoDbConn) {
    // list messages
    mongoDbConn.collection(collectionName).insert(data, function (err, cursor) {
      if (err) {
        res.send('mongodb message list failed');
      } else {
        res.send("Inserted the event successfully and reference ID is " + data._id);
      }
    });
  }
});

So this way can easily connect to your MongoDB on bluemix service from your node js application.
Note:You can combine all the 3 code snippets in order and it will work.
If you face any issues in connecting you can comment here.
Hope it helps someone!

Advertisements

Creating new database and user in mongodb on bluemix using Mongo CLI on windows

One we have Compose for Mongodb service on bluemix we want to create different users and add the permission levels according to database.Creating users directly from bluemix GUI is not possible.We need to use Mongo CLI for this.
On MAC,it is quite easy but on Windows it is difficult and we need to install SSL enabled mongodb to connect to mongodb on bluemix.

The software can be downloaded from the following link

Once the software is installed , open CLI and go to folder where mongodb is installed.
Then to connect to mongodb we need to paste uri_cli which is the ssl uri which u will find in credentials

mongossl.PNG

Then you will be connected to mongodb service on bluemix

mongocoonected

Now to see the available databases ,

showdbs

To create a new database
newdb.png
To create a new user and assign a role to the user use the following command

db.createUser(
  {
    user: "UserName",
    pwd: "Password",
    roles: [
       
       { role: "readWrite", db: "testdb" }
    ]
  }
);

usercreate

This way we can easily create user and assign permissions.To list the users use command >show users

Hope it helps someone!