NodeJS / MongoDB

Warning

drie push is currently in beta and the APIs are subject to change as we stabilise the product. If something that was working stops working, please come back to the documentation to see if new behaviour is documented. If there’s no explanation, then please let us know.

This quickstart will go through the steps of:

  • Creating a NodeJS/Express 4 bookmarking app
  • Connecting it to mLab MongoDB, a leading database-as-a-service provider
  • Deploying the app on the drie push platform

Note

Please fulfill these prerequisites before doing this quickstart.

  1. NodeJS installed on your local machine.
  2. mLab MongoDB account
  3. mLab MongoDB database
  4. mLab MongoDB database user authorised to use the database above

1. Create a new Nodejs/Express 4 app

We will be creating an app that stores your favourite bookmarks from scratch. Let’s create a project called drie-bookmarker-nodejs:

$ mkdir drie-bookmarker-nodejs
$ cd drie-bookmarker-nodejs

Open your favourite text editor and create Procfile file, which notifies the drie platform what to run:

$ vi Procfile

Paste the content below into your Procfile:

web: node index.js

Then, create the package.json file, which states the dependencies for our app:

$ vi package.json

Paste the content below into your package.json:

{
  "name": "drie-bookmarker-nodejs",
  "version": "0.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "BSD-2-Clause",
  "dependencies": {
    "mongoose": "~4.6.4",
    "express": "~4.14.0",
    "json": "~9.0.4",
    "body-parser": "~1.15.2"
  }
}

Lastly, create index.js, which is the main file that runs the bookmarker app:

$ vi index.js

Paste the content below into your index.js:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

var app = express();

app.set('port', (process.env.PORT || 5000));
app.set('mongodb_uri', process.env.MONGODB_URI);
app.use(express.static(__dirname + '/public'));

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var Bookmark = mongoose.model('bookmark', {name: String, url: String});

// Connect to MongoDB
mongoose.connect(app.get('mongodb_uri'));

app.get('/bookmarks', function(req, res) {
  mongoose.model('bookmark').find(function(err, bookmark) {
    res.send(bookmark);
  });
});

app.post('/bookmark/add', function(req, res) {
  var newBookmark = new Bookmark( req.body );

  newBookmark.save(function (err, newBookmark) {
    if (err) return console.log(err)

    console.log('saved to database:' + JSON.stringify(req.body))
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ "status": "added" }));
  });
});

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'));
});

Note

We are using the Mongoose MongoDB driver for this project. It allows us to model objects in our NodeJS app and map it to MongoDB.

Warning

The free tier of mLab does not provide TLS encryption. For production use, we strongly advise using a mLab tier with TLS to secure your database traffic between drie and mLab.

For in-depth connection settings regarding mLab, please check out these links:

2. Create a local git repo and set it up to deploy to drie push

$ git init
$ git add *
$ git commit -m "Created drie bookmarker app and setting up to deploy to drie."

After you’ve created your local git repo, we now set up the remote drie push git repo where we push our code.:

$ app_name=$(curl -s http://m.rang.app.push.drieapp.co)   # generates a random app name for you
$ echo "Your app is called ${app_name}"               # you can see what app name was generated for you
$ git remote add drie ${app_name}.app@push.drieapp.co:code.git

3. Deploy you code to drie push

$ git push --set-upstream drie master

This pushes up your code to drie push where it builds on the remote server.

4. Set the MONGODB_URI environment variable in drie push

You will need to get the MongoDB URI from mLab. Log into your mLab account and go to: https://mlab.com/databases/<your-database-name>

You can see the dbuser and dbpassword that you set up against your database here: https://mlab.com/databases/<your-database-name>#users

The MongoDB URI pattern should be mongodb://<dbuser>:<dbpassword>@<someserver>.mlab.com:<portnum>/<your-database-name>

To set the MONGODB_URI environment variable in drie push, run the command below, replacing the placeholders for dbuser, dbpassword, someserver, portnum and your-database-name:

$ ssh ${app_name}.app@push.drieapp.co configure environment -s MONGODB_URI=mongodb://dbuser:dbpassword@someserver.mlab.com:portnum/your-database-name

5. Confirm that your bookmarking app works

Try to add a bookmark:

$ curl -X POST -H 'Content-Type: application/json' -d '{"name":"drie", "url":"https://drie.co"}' http://master.${app_name}.app.push.drieapp.co/bookmark/add

Confirm that your bookmark was added:

$ curl http://master.${app_name}.app.push.drieapp.co/bookmarks

You should see an empty list where you can add new bookmarks. Congratulations! You’ve successfully deployed your NodeJS / mLab MongoDB app on drie push!