Setting up MongoDB with Autoparts

Last Updated on: 28 May 2014

This guide walks through how you can setup a MongoDB database on your Nitrous.IO box.

Prerequisites

  • Nitrous.IO box with the package manager Autoparts installed. To ensure Autoparts is installed, run the command parts within the terminal. Take a look at the Autoparts guide for installation instructions.

Installing MongoDB

To install MongoDB with the autoparts package manager, run the following command:

parts install mongodb

Configuration

To connect to MongoDB you will need to first start the database:

parts start mongodb

You can launch the console client by running the following command:

mongo

If this didn’t work immediately after starting mongodb, try again in a few seconds. The MongoDB process may still be starting up.

Once you are connected you can configure your web app to utilize MongoDB. Here are the default configuration in order to get started:

  • Mongodb.conf location: ~/.parts/etc/mongodb.conf
  • Username: action
  • Host: 127.0.0.1
  • Port: 27017

If you are wanting to connect to an external database, please view the guide on Connecting to MongoLabs.

Connecting to MongoDB with Rails

Before making configuration, start up MongoDB with the following command:

parts start mongodb

When building a Rails app, run the following command to skip active record and test unit:

rails new myapp --skip-active-record --skip-test-unit

Rails 4 requires the latest version of mongoid, which also includs bson_ext as a dependency. Add the following lines to your Gemfile:

gem 'mongoid', git: 'https://github.com/mongoid/mongoid.git'
gem 'bson_ext'

Once the Gemfile has been updated, run the following:

bundle install

Next, generate the configuration:

rails g mongoid:config

Connecting to MongoDB with Node.JS

Before making configuration, start up MongoDB with the following command:

parts start mongodb

Use the package manager NPM to install the driver:

npm install mongodb

Next we will write some code that will allow our Node.JS app to connect to MongoDB.

Create a new file titled app.js, and add the following contents:

var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");
    }
    db.close();
});

Save the file and try running it with Node:

node app.js

If everything went smoothly you should see the output “successfully connected to the database”.