Structuring an Express MVC API – Part 1

Summary

You may be thinking “Huh? MVC for an API?” Well yes, we are discussing MVC for an API. This is part one of a mini-series of posts discussing how to setup a simple Express API using the MVC pattern. In this part I will be giving you a brief introduction into the MVC pattern itself as well as a sneak peak at some of the code in the Todo sample app.

Why learn about this?

You see even though you are creating a RESTful API it is still very important to have a well thought out structure for your application. In today’s post I will discuss an excellent way of separating your Express code so that it is nicely organized and easy to extend.

All code from this post is located on my GitHub page.

What is MVC?

As you may have guessed an MVC application consists of three fundamental parts:
– Model
– View
– Controller

The pattern itself is very common and can be applied at both the project level as well as the sub-project level. For example the front-end of a MEAN application is written in AngularJS and AngularJS lends itself to using an MVC pattern just in the client tier alone. Then, when you implement the back-end you also implement this pattern as I will show you.

Models

Models simply represent the data. An example of a model would be any POJO (Plain Old JavaScript Object). Let’s say that we are creating a ToDo application (Nice! We are creating a Todo App). In our application the Model would be a simple Todo object. Since this is a MEAN blog our model is stored in MongoDB then retrieved via Mongoose. Both Mongoose and Mongo will be discussed in future posts.

Here is an example of a Model from our Todo application.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ToDoSchema = new Schema({
    description: String,
    dueDate: {
        type: Date,
        default: Date.now
    },
    isComplete: {type: Boolean, default: false}
});

mongoose.model('Todo', ToDoSchema);

Views

As I mention we are building an Express API so in this case the view is simply the HTTP response received from our API. Although since we are creating a Todo application we will also have plain html views as well.

So there you have it. The View in MVC conceptually represents the display of our data whether that is HTML, JSON, or something else.

Here is the JSON view of a Todo:

{
    "__v": 0,
    "description": "Write blog post",
    "_id": "54c269e6f08121ff125cae74",
    "isComplete": false,
    "dueDate": "2015-01-23T15:33:58.078Z"
}

You can disregard the _id and the __v since these will be discussed in an upcoming MongoDb post.

Controllers

Controllers are the core of the MVC pattern. You can think of them as the glue between the Model and the View. This is the only layer which has knowledge of the other two layers.

The main purpose of the Controller is to retrieve data from the Model and hand it back over to the View. Additionally if there is any logic that needs to be applied this is the place to do that as well.

Here is a quick snippet of a Controller using Mongoose to retrieve the document data.

var Todo = require('mongoose').model('Todo');
exports.create = function (req, res, next) {
    var todo = new Todo(req.body);
    todo.save(function (err) {
        if(err){
            return next(err);
        } else{
            res.json(todo);
        }
    })
};

exports.list = function (req, res, next) {
    Todo.find({}, function (err, todos) {
        if (err) {
            return next(err);
        } else {
            res.json(todos);
        }
    });
};

In the above example the Model is represented by the Todo mongoose object and the view is represented by the JSON sent in the response object.

Up Next

In the next post we will dig into how you can start organizing your application to utilize this pattern.

2 thoughts on “Structuring an Express MVC API – Part 1”

  1. yes, the ever present MVC framework, generally a smart way to design applications, as it has a significant tendency to lend to extensibility.

    interested to see what you come up with…

    on an unrelated note, is a good friend when linking to pages of site… I want to open the page, but stay on your site…

    1. Hey Mike, thanks for reading the post.

      Regarding the links I’m using MarkDown to write the posts and don’t really want to break into straight HTML anchors. Also, I’m a fan of the control/command click instead. I do appreciate the feedback though.

Leave a Reply

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