Connecting a HTML5 application to a MongoDB instance via MongoLab REST API10 Dec 2011
I needed a free, document based, online data store so that I could quickly build a HTML5 prototype. As an exercise, I quickly whipped up a simple application that can store basic contact details of people.
Getting Started with MongoLab
To get started with MongoLab is really easy. Simply create your account, your database and your first collection and your good to go. The only reference document you need for this exercise is the MongoLab REST API docs
First things first: Adding data to your MongoDB using REST
I am only going to show you the absolute basics here, so no security, validation, callbacks or fancy UI designs – just the basics! I built this by creating a simple HTML5 form and I used XMLHttpRequest API to send the data to MongoLab.
Here are the code snippets, first the HTML:
<form id="myform" name="myform"> <input id="name" type="text" name="name" placeholder="Name"><br> <input id="email" type="email" name="email" placeholder="Email"><br> <input type="button" onclick="send(this.form);" value="Save"> </form>
var xhr = new XMLHttpRequest(); xhr.open("POST", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION?apiKey=YOUR-API-KEY", true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(json);
When you load your page you will be able to add a new record to the database. You can check that it has arrived at the database by logging into mongolab.com and viewing the collection.
Next up: Display a collection of items
<ul id="result"> </ul>
var request = new XMLHttpRequest(); request.open("GET", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION?apiKey=YOUR-API-KEY"); request.send(null);
View a single document
var queryString = window.top.location.search.substring(1); id = queryString.substring(3,queryString.length); var request = new XMLHttpRequest(); request.open("GET", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION/" + id + "?apiKey=YOUR-API-KEY"); request.send(null);
Edit a document
var xhr = new XMLHttpRequest(); xhr.open("PUT", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION/" + getId() + "?apiKey=YOUR-API-KEY", true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(json);
Delete a document
Finally, we want to be able to delete a document. This is really easy as shown. Notice you need to send null like before because there is no payload.
var request = new XMLHttpRequest(); request.open("DELETE", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION/" + id + "?apiKey=YOUR-API-KEY"); request.send(null);
Thankfully, with the excellent service provided by MongoLab.com developers are able to build nosql document database driven applications in no time and at no cost!