Building the server-side app

We’ll start by building the server-side section of the app. We’ll build a series of routes that will provide Create, Read, Update, Delete (CRUD) operations on our MongoDB database. We will expose these as REST APIs.

Let’s write our models and custom routes into a separate route file to keep things clean.

Creating the Mongoose schemas

We first start by loading the mongoose library and establishing a connection to the angcms database. We add the following highlighted code in the angcms/app.js file:

var app = express();    
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/angcms');
var db = mongoose.connecetion;

For this application, we are going to need two schemas: the Pages schema and the Admin Users schema. Let’s create these now.

We’ll create a new folder named models, and create our page.js file with the following code in it:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
    var Page = new Schema({
        title: String,
        url: {type:String, index:{unique:true}},
        content: String,
        menuIndex: Number,
        date: Date    });
    var Page = mongoose.model('Page', Page);
    module.exports=Page;

The following table gives a description for the fields in the schema:

Fields Description
title The title of the content page.
url The SEO-friendly alias that will be used to identify the page. Note that we are setting its index to unique as we don’t want duplicate URL aliases.
content The content of the page.
menuIndex An integer that defines the menu sequence of the pages in the navigation bar.
date The date when this document was last updated.

Next, we create the schema for our admin users in the models/admin-users.js file as follows:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var adminUser = new Schema({
        username: String,
        password: String
    });
    var adminUser = mongoose.model('adminUser', adminUser);
module.exports=adminUser;

As you can see, we are keeping things very simple, with our admin user’s schema only storing the username and password.

Creating CRUD routes

Now, we’ll start writing the routes for the CRUD operations; we’ll start by generating the listing page.

Create a new file, routes/api.js, in the routes folder, and add the following code:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Page= require('../models/page.js');
var adminUser= require('../models/admin-users.js');

/* User Routes. */

router.get('/', function(req, res) {
  res.send('Welcome to the API zone');
});

router.get('/pages', function(request, response) {

        return Page.find(function(err, pages) {
            if (!err) {
                return response.send(pages);
            } else {
                return response.send(500, err);
            }
        });
    });

module.exports = router;

What the preceding code does is that it runs the find() method on the Page schema and returns the list of pages found. In case of an error, it would return a status code of 500 and display the error message. We need to get back to our app.js file and add the following lines to create these routes:

var api = require('./routes/api');

app.use('/api', api);

Add the preceding two lines within the respective sections of the app.js file.

Make sure that app.use('/api', api); is called before app.use('/', routes);. This will ensure that the /api routes get higher priority than the others.

On the terminal, stop and restart the npm using the npm start command. Note that you need to restart the web server every time you make a change to the server-side code.

On the browser, navigate to http://localhost:3000/api/pages.

You should see empty square brackets. This means that our current collection is empty.

Adding a new entry to the collection

Next, let’s write the route to add data to our collection. We will continue adding it to the routes/api.js file as follows:

router.post('/pages/add', function(request, response) {
    var page = new Page({
        title: request.body.title,
        url: request.body.url,
        content: request.body.content,
        menuIndex: request.body.menuIndex,
        date: new Date(Date.now())
    });

    page.save(function(err) {
        if (!err) {
            return response.send(200, page);

        } else {
            return response.send(500,err);
        }
    });
});

As we need to pass data to our server script, we will use the post method instead of get. Next, we create a new instance of our page object and pass the request parameters from our post data. We then call the save method, which does the actual task of saving this data into the collection.

We can test this route by simulating the post action using either the browser’s developer tools console or Firebug console. Alternatively, there are quite a few REST clients available as browser extensions and add-ons that can help you simulate the post action.

Try to create a couple of pages using this method, and run http://localhost:3000/api/pages to verify that this data is being saved and returned as a JSON response. You’ll also notice an additional key named _id being saved along with each of these nodes. We will be using the _id key for our delete and update operations

 

Chapter 2 of 12