Connection with MongoDB

What You'll Need

Backbench account - Sign Up, the personal account will always remain free to use.

mLab account - Create your free mLab account. When that’s complete, you can add as many database subscriptions as you want.

Prerequisites for the app

  1. Sign in to the Backbench account.

  2. Select +, in the upper right corner to create a Bench. For example, say "dbench" and select CREATE or hit Enter.

  3. Go to mLab account.

  4. At Home page, Select Create new to create a new database then select a Cloud Provider and Plan Type, for example, say AWS and Plan Type as Sandbox (a free option) and click CONTINUE.

  5. Select an AWS region, for example, say US East (Virginia) (us-east-1) and click CONTINUE. Finally, give your DATABASE NAME, for example, say "firstdb" and click CONTINUE.

Backend (Node.js)

  1. Adding package.json module. (Select +, in the upper right corner to create a Module.)

{
    "dependencies": {
        "mongodb": "2.2.19"
    }
}

A package.json file lists the packages that your project depends on. allows you to specify the versions of a package that your project can use using semantic versioning rules.

2. Go to your mLab Home Page and select newly created Database, then user's tab to add a Database User by providing a name and password. 3. Create a module on Backbench, for example, say "mongodb.js", then copy and paste following code for backend.

var MongoClient = require("mongodb").MongoClient;

exports.endpoint = function(req, cb){
    var url = "mongodb://<dbuser>:<dbpassword>@ds135704.mlab.com:35704/sampledb";
    MongoClient.connect(url, function(err, client){
        if (err) {
            bb.log(err)
        } else {
            bb.log(client)
            var dbo = client.db("sampledb");
            dbo.createCollection("customers", function(err, res){
                cb(undefined, {msg:"Collection created..."})
                bb.log("Collection created!");
                client.close();
            })
        }
        
    })
}

Replace the url above with your MongoDB URI and enter your Database user credential.

Don't forget to map this endpoint, (from the endpoint section at Backbench)

https://<backbench username>-<name of your bench>.backbench.io/mongocreate.

You just ran the above created module and a collection was created in the mLab Database.

See mLab docs for reference.

Last updated