Introduction to Backbone -2

With a little background on Backbone we will now start developing an application for an Image sharing application. The application will support the following functionalities
1. Users can tag/hide and remove images.
2. The application will display the images which have been uploaded

For this post, we will set up a server using Node.js which will support a REST based API. We will use MongoDB as a datastore just to make things a little more fun.

The API which we will support would be

URL HTTP Method Operation
/api/images get Get an array of all images(not hidden)
/api/images post Upload a new image
/api/image/:id delete Delete an image
/api/image/:id put update a picture

This post also assumes that you have Node.js, npm and MongoDB installed. Also create a package.json at the root of your project and add dependencies for express, path and mongoose. The package.json should look like

{
"name" : "backbone-photoapp",
"version" : "0.0.1",
"description" : "A sample photosharing application",
"dependencies" : {
"experess" : "3.x",
"path" : "~0.4.9",
"mongoose" : "~3.5.5"
}
}

Next run npm install at the root of your project.

Lets create up a simple http server using Express.js

(For more details on the Express.js web framework please refer to Express.js Guide)

Implementing the Server

Start by creating a file called server.js in the root of the project.


var application_root=__dirname;
var express=require('express');
var path=require('path');
var mongoose=require('mongoose');

We start by specifying the module dependencies for Express.js, path (Contains utilities for dealing with file paths) and mongoose(MongoDB integration).

We also set the application root to the directory in which the script currently resides, which in our case is the root of the project.

We next create an application with express and configure the server


var app=express();

app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(application_root,'/static'));
});

app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
app.use(express.errorHandler());
});

In order to configure the server, we do the following
1. We parse the request body.
2. We perform route lookups based on URL and HTTP methods(get, put, post etc).
3. We specify where to serve static content from.
4. We specify which errors would be displayed for development(all errors) and production.

As a last step, we configure the server to listen on a specific port.

var port = 3030;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode',
port, app.settings.env );
});

The complete listing is given below


var application_root=__dirname;
var express=require('express');
var path=require('path');
var mongoose=require('mongoose');
var app=express();

app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root,'site'));
});

app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
app.use(express.errorHandler());
});

var port = 3030;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode',
port, app.settings.env );
});

Running the above code using node server.js would output

Express server listening on port 3030 in development mode

Setting up the Datastore

In order to set up the datastore, we need to define the schema and connect to it.

Defining the Schema

For the sake of keeping the example simple, we will define a very simple schema. The images will be have attributes for the image source, title, the name of the user who uploaded the image and any tags which the user associated with the image.

Ideally, we would define the schema in a separate file, however for the sake of simplicity, we will keep everything within server.js for the moment. We create the schema using the mongoose.Schema constructor. (For more details on Mongoose, please refer to the Mongoose API).

Add the following lines to server.js.


var Image= new mongoose.Schema({
imageSrc:String,
title:String,
uploadedBy:String
tags:String
});

Connecting to the datasource

In order to connect to MongoDB, we can use either the default connection provided by mongoose or use mongoose.createConnection. The code below shows a couple of variations to connect to the datasource.

The default connection provided by mongoose can be used as

mongoose.connect('mongodb://user:pass@localhost:port/db_name');

The same can be accomplished using mongoose.createConnection


mongoose.createConnection('mongodb://user:pass@localhost:port/db_name');

createConnection also accepts a set of options


var opts = { server: { auto_reconnect: false }};
mongoose.createConnection('mongodb://user:pass@localhost:port/db_name',opts);

A few other options are shown below


var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'password' };
mongoose.createConnection('localhost', 'database', port, opts);

var db=mongoose.createConnection(); // initialize the connection
db.open('localhost', 'database', port, [opts]); //connect later

Retrieving a Model

In order to retrieve a model, we make use of the mongoose.Model. The first argument is the name of the model and the second one specifies the actual Schema which we defined above.


var ImageModel = mongoose.Model('Image',Image);

Now thats all that we need to setup the schema.
In the next couple of posts, we will create the routes and define the REST API, as well as build the front-end using backbone

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>