Adding New Models, Controllers and Routes in Express.js

Follow the steps below to create a new model, controller, and route for an Express application installed through MEAN.JS. These instructions are adapted from a tutorial found at the URL “http://www.bradoncode.com/tutorials/mean-stack-tutorial-part-2-server-side/”.

MEAN.JS-Widgets

1. If you have not already done so, follow the steps in a previous post to create a new application named “MEANTestApp” using MEAN.JS.

2. Open a command prompt window, navigate to the MEANTestApp directory within it, and then run the following commands. When prompted, specify the module “widget” and accept the default name.

	npm install -g yo
	npm install -g generator-meanjs
	mkdir modules\widget
	yo meanjs:express-model widget
	yo meanjs:express-controller widgets
	yo meanjs:express-route widgets

3. In a text editor, open the file “modules\widget\server\models\widget.server.model.js”, locate the text “// …”, replace it with the text below, and save the file:


	created: 
	{ 
		type: Date,   
		default: Date.now 
	},
	description: 
	{
		type: String,
		default: "",
		trim: true
	},
	name: 
	{
		type: String,
		default: "",
		trim: true,	 
		unique : true,
		required: "Name cannot be blank."
		// validate: [validateLength, "name must be 15 chars in length or less"]	
	}

4. In a text editor, open the file “modules\widget\server\routes\widget.server.routes.js”, locate the text “// …”, replace it with the text below, and save the file:


	var widgets = require("../controllers/widget.server.controller");
	
	app.route("/widgets")
		.get(widgets.list)
		.post(widgets.create);

	app.route("/widgets/:widgetId")
		.get(widgets.read)
		.put(widgets.update)
		.delete(widgets.delete);

	app.param("widgetId", widgets.widgetByID);

5. In a text editor, open the file “modules\widget\server\controllers\widget.server.controller.js”, replace the generated text with the text below, and save the file:


	"use strict";

	var path = require("path");
	var mongoose = require("mongoose");
	var errorHandler = require(path.resolve("./modules/core/server/controllers/errors.server.controller"));
	var Widget = mongoose.model("Widget");
	var _ = require("lodash");

	exports.create = function(req, res) 
	{
		var widget = new Widget(req.body);
	
		widget.save
		(
			function(err) 
			{
				if (err) 
				{
					return res.status(400).send
					(
						{ message: errorHandler.getErrorMessage(err) }
					);
				} 
				else 
				{
					res.status(201).json(widget);
				}
			}
		);
	};

	exports.read = function(req, res) 
	{
		res.json(req.widget);
	};

	exports.update = function(req, res) 
	{
		var widget = req.widget;
	
		widget = _.extend(widget, req.body);
	
		widget.save
		(
			function(err) 
			{
				if (err) 
				{
					return res.status(400).send
					(
						{ message: errorHandler.getErrorMessage(err) }
					);
				} 
				else 
				{
					res.json(widget);
				}
			}
		);
	};
	
	exports.delete = function(req, res) 
	{
		var widget = req.widget;
	
		widget.remove
		(
			function(err) 
			{
				if (err) 
				{
					return res.status(400).send
					(
						{ message: errorHandler.getErrorMessage(err) }
					);
				} 
				else 
				{
					res.json(widget);
				}
			}
		);
	};
	
	exports.list = function(req, res) 
	{
		Widget.find().sort("name").exec
		(
			function(err, widgets) 
			{
				if (err) 
				{
					return res.status(400).send
					(
						{ message: errorHandler.getErrorMessage(err) }
					);
				} 
				else 
				{
					res.json(widgets);
				}
			}
		);
	};
	
	exports.widgetByID = function(req, res, next, id) 
	{
		if (mongoose.Types.ObjectId.isValid(id) == false) 
		{
			return res.status(400).send
			(
				{ message: "Widget is invalid!" }
			);
		}
	
		Widget.findById(id).exec
		(
			function(err, widget) 
			{
				if (err) return next(err);
				if (widget == null) 
				{
					return res.status(404).send
					(
						{ message: "Widget not found." }
					);
				}
				req.widget = widget;
				next();
			}
		);
	};

5. Run “mongo” at a command prompt. At the Mongo prompt, enter the following commands:

use mean-dev
db.widgets.insert({name : "Widget1", description: "This is a widget."})

6. At the command line, enter the command “gulp” to start the MEANTestApp application.

7. Open a web browser and navigate to the URL “http://localhost:3000/widgets”. Some JSON text representing the database entry for “Widget1” should appear.

Advertisements
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

One Response to Adding New Models, Controllers and Routes in Express.js

  1. Nakul Chawla says:

    I am trying to add a model using yo meanjs:express-model category, and i am getting asked “Which module does this controller belongs to?”, is there a way to create the model in a new folder that has its model and test cause this model doesn’t belong to either of my controllers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s