Quickest way to get going with Node.js and MongoDB – using the mongodb Node driver and a free MongoDB instance in the cloud with mLab

0
Share this on .. Tweet about this on TwitterShare on LinkedIn14Share on Facebook2Share on Google+0Email this to someoneShare on Tumblr0Buffer this page

imageWhile preparing for a workshop on Node.js, I ran into the by far quickest way to get some a simple Node.js application  running against a  MongoDB database. I stumbled into mLab (https://mlab.com/) for database hosting. This company offers various plans for cloud based MongoDB environments – including a free plan for an environment with up to 500 MB data. Plenty for a quick trial of the Node.JS => MongoDB interaction. So here are my steps:

1. Sign Up for an mLab account (confirm email address via link in email)

2. Login to mLab

3. Create a new deployment of type Sandbox:

image

Set database name: world

image

and press the button to create the new MongoDB deployment.

4. After a little while, the database is created. Click on the Users tab to create a user – authentication is required for remote access:
image

image

Download source from GitHub Repository: https://github.com/lucasjellema/nodejs-mongodb-quickstart

 

5. optional: Load data into this cloud based MongoDB database, for example by loading a csv file. This requires a local installation of theMongoDB toolset. Navigate to directory country-queries. The run this command:

mongoimport –host dsYOURINSTANCE.mlab.com:yourport –db world –collection countries –drop –file countries.csv  –type csv –fieldFile countriesFields.txt -u YOURUSERNAME -p YOURPASSWORD

 

SNAGHTML1abdb3

 

6. Create a new Node application using npm:

npm init mongodb-client

 

7. Download and Add a dependency for mongdb driver:

npm install mongodb –save

 

8. Create app.js with the following code:

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

var cloud = true;

var mongodbHost = '127.0.0.1';
var mongodbPort = '27017';

var authenticate ='';
//cloud
if (cloud) {
 mongodbHost = 'YOURHOST.mlab.com';
 mongodbPort = 'YOURPORT';
 authenticate = 'YOURUSER:YOURPASSWORD@'
}

var mongodbDatabase = 'world';

// connect string for mongodb server running locally, connecting to a database called test
var url = 'mongodb://'+authenticate+mongodbHost+':'+mongodbPort + '/' + mongodbDatabase;


// find and CRUD: http://mongodb.github.io/node-mongodb-native/2.0/tutorials/crud_operations/
// aggregation: http://mongodb.github.io/node-mongodb-native/2.0/tutorials/aggregation/

MongoClient.connect(url, function(err, db) {
   assert.equal(null, err);
   console.log("Connected correctly to server.");
//var cursor = collection.find({});
    // find top 20 countries by  size
    db.collection('countries').find({},{"sort": [["area",-1]]}).limit(20).toArray(function(err, results){
    console.log("Country One " +JSON.stringify(results[0])); 
    console.log("Name of Country Four " +results[3].name+ " and size: " +results[3].area);

      db.close();
      console.log("Connection to database is closed.");
    });

}) //connect()

And run the application:

node app

image

9. Instead of creating your own new application, run the files index.js, query.js and crud.js from the GitHub repository  (do not forget to run npm install in the directory that contains these sources, to download the mongodb module and make sure that you set the right values for mongodbHost, mongodbPort and authenticate)

image

Set connection details:
SNAGHTML25b902

Then

node index (or node query or node crud)

image

Share this on .. Tweet about this on TwitterShare on LinkedIn14Share on Facebook2Share on Google+0Email this to someoneShare on Tumblr0Buffer this page

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director and Oracle Developer Champion. Solution architect and developer on diverse areas including SQL, JavaScript, Docker, Machine Learning, Java, SOA and microservices, events in various shapes and forms and many other things. Author of the Oracle Press books: Oracle SOA Suite 11g Handbook and Oracle SOA Suite 12c Handbook. Frequent presenter on community events and conferences such as JavaOne, Oracle Code and Oracle OpenWorld.

Leave a Reply