# TypeScript and the MEAN Stack: Getting started Part 2

### Introduction

In my previous post, we got a brief idea on what TypeScript and the MEAN stack are. We installed the essential tools and put together a simple node/express application. Here, we will continue from where we left off, connecting the application to MongoDB.

### Some Quick Housekeeping

Before we get started with hooking up the application with MongoDB, let’s make the following file and folder changes:

1. Create new folder called app at the root level of the project.
2. Move the routes and view folders to the app folder.
3. Rename app.ts to server.ts.
4. Rename index.ts and user.ts in the app/routes folder to indexRoutes.ts and userRoutes.ts respectively. Module dependencies should also be updated.
5. Create a new folder called controllers in the app folder and add a new TypeScript file userController.ts to it.
6. Create a new folder called models in the app folder and add a new TypeScript file userModel.ts to it.

The app folder should have the following structure:

### Hooking up the application to MongoDB

We are going to create a simple entity and attempt to create and retrieve some instances, using MongoDB for persistence. There are quite a few ways to achieve this, but for the time-being, we are going to use mongoose.

#### Install mongoose

We can add mongoose via npm. After the package is retrieved, let’s get the mongoose definition file from the definitely typed repository and add it to Scripts/typings/mongoose.

#### Update server.ts

The module dependencies in server.ts should be as follows:

/*
* Module dependencies.
*/
import express = require('express');
import routes = require('./app/routes/indexRoutes');
import user = require('./app/routes/userRoutes');
import http = require('http');
import path = require('path');
import mongoose = require('mongoose');

In the same file, we should add that we want to connect to the database:

/*
* Main application entry file.
*/
mongoose.connect('mongodb://localhost/mean-type-dev');

var app = express();

#### Create the schema and interface

For the purposes of this session, we will create a User entity with the field “name”. The file userModel.ts will contain the following:

import mongoose = require("mongoose");

export var userSchema = new mongoose.Schema({
name: String
});

export interface IUser extends mongoose.Document {
name: string;
}

export var repository = mongoose.model<IUser>("User", userSchema);


There is a bit of duplication here. Mongoose requires the use of schema definition code for data validation, type casting, etc. In TypeScript, we also need to define interfaces that extend mongoose documents. This is not ideal, and it would obviously be better if we can get the two aspects working better together. This is a topic that would require further investigation. For the time being, this will have to work.

#### Create the controller

My aim is to keep the controller as the entry point of the web requests and to maintain whatever application logic is needed. The controller will take the request, process the data in some meaningful way via the repository, and depending on the result, provide a suitable response.

So userController.ts will look like this:

import express = require("express");
import mongoose = require("mongoose");
import userModel = require("../models/userModel");

import IUser = userModel.IUser;
import repository = userModel.repository;

export function createUser(req: express.Request, res: express.Response) {

repository.create({ name: userName }, (error) => {
if (error) {
res.send(400);
} else {
res.send("user " + userName +" created");
}
});
}

export function retrieveUser(req: express.Request, res: express.Response) {

repository.findOne({ name: userName }, (error, user) => {
if (error) {
res.send(400);
} else {
res.send("user with name " + user.name + " retrieved");
}
});
}

#### Update routes

To keep the aforementioned idea, the routing files should be kept as simple as possible. This was kept in mind for the new operations in the controller that need to be exposed via userRoutes.ts:

import express = require("express");
import controller = require("../controllers/userController");

/*
* User Routes
*/
export function list(req: express.Request, res: express.Response) {
res.send("respond with a resource");
};

export function create(req: express.Request, res: express.Response) {
controller.createUser(req, res);
};

export function read(req: express.Request, res: express.Response) {
controller.retrieveUser(req, res);
};

Back on server.ts, let’s update the routing code:

app.get('/', routes.index);
app.get('/users', user.list);
app.post('/users/:name', user.create);

### Tools

We’re almost set to give it a spin. Let’s go ahead and grab some more tools that will help us with testing:

• Any REST client. I use Postman and it suits my needs.
• Any MongoDB management tool. My preference here is Robomongo.

### Some tests

Now we can run the application and fire up a REST client. Again, keeping things simple, let’s go ahead and add the URL below and setting the method to POST. Sending the request will give us a response that the user was created:

Now that we created a user, we can also retrieve with the same URL and with the GET method:

So far, so good. Let’s just check to see that we do have something stored in our database. Using Robomongo, we add our local connection, which should appear automatically in the connections dialog:

The database “mean-type-dev” should be found, along with the collection users. Looking at the users collection, we find a user, which is in fact the user we created:

So there you have it. We now have a node application that can play nicely with MongoDB, with everything written up in TypeScript.

### Conclusion

Today we were able to hook up our application with MongoDB via mongoose and perform some basic database operations. My next post will focus more on the client side, digging into angular.

Cheers!

# TypeScript and the MEAN Stack: Getting started Part 1

### Introduction

Two areas that have gained my attention lately are TypeScript, Microsoft’s offering in making JavaScript more attractive for use in large-scale applications, along with the MEAN stack, a collection of open-source libraries that allows the use of JavaScript for web application development. I think it would be an interesting experiment to implement a basic MEAN stack in TypeScript instead of JavaScript.Today I will delve into what it takes to get the essentials working on a Windows development environment and create a simple project in Visual Studio.

### Install the essentials

#### Prerequisites

There is a lot of information get the MEAN stack up and running on Linux and Mac environments and less information for Windows environments, even though the process is quite straightforward. At least for this tutorial, I assume you have a machine with some version of Windows installed, along with your favourite IDE. I have Windows 7 (Not yet ready/willing to jump to 8 yet) along with Visual Studio 2013. My plan is to start with the Node.js tools for Visual Studio (More on that below) and then move on to another IDE such as Sublime Text.

#### Git

Git will be used for source control. Git’s popularity can’t be ignored, and I hope to release a reasonable take sometime in the near future. Git for Windows provides all the necessary tools to get Git running on Windows, along with a nice bash shell. Despite being a sucker for Windows, I’ve always enjoyed the Unix-style commands over the command prompt.

#### MongoDB

MongoDB provides the data storage component of the MEAN stack. More specifically, it is a document-oriented NoSQL database. Along with the benefits of availability and scalability that we get from most NoSQL databases, all data is stored in JSON-like documents, providing a nice fit with JavaScript.

Once MongoDB is installed, we can run MongoDB as a Windows Service (Make sure you run as administrator):

$mongod --logpath "C:\path\to\logfile" --dbpath "C:\path\to\dbdir" --install And to remove the service: $ mongod –remove

#### Node.js

Node.js is a platform that allows the development of scalable server-side applications with JavaScript. In our case, node will run the compiled TypeScript code on the server. node also comes with npm, which provides a vast collection of modules that expand on what node can provide.

Packages can be installed locally to a specific project:

$npm install <package> Packages can also be installed globally: $ npm install -g <package>

#### TypeScript

For this tutorial, Visual Studio 2013 will be used to create and compile the project. TypeScript is available with Visual Studio 2013 Update 2. In the future, command-line tools will be used, so it’s worth installing now:

\$ npm install –g typescript

#### Node Tools

Node.js Tools for Visual Studio is still in beta, but it provides an excellent starting point for putting together a node project, especially if you are familiar with using Visual Studio.

### Create a Project

Once everything is installed, we’ll create a Basic Express Application in Visual Studio:

Upon generating the application, we get the following project:

If you’re coming from a pure .NET world, there’s some new things for you:

• The views generated are not in html, but in Jade. Jade files will be discussed in a future post.
• Style-sheets is not written in CSS, but in a pre-processor language called Stylus.
• The file package.json contains information on the npm packages the project depends on.

So a few things different from a standard node/express project. Obviously, there are no JavaScript files, with TypeScript files taking their place. Another point of interest are the typing files. For each of the installed npm packages, there is a type definition file, which allows the use of the npm packages with stronger type definitions in TypeScript. A vast collection of type definitions for several popular packages can be found at the Definitely Typed website. Seeing that we are there. I grabbed the latest versions of the definition files that I will be using in the project.

#### I see Express

If you look at the npm packages, you can see that Express is already installed as a dependency. Express sits on top of node and provides a framework to run node as a more complete web application, including the use of views, routing, etc.

#### I don’t see Angular

Angular is not an npm package, but it’s a framework that will be used client-side. Since the focus has been on server-side, Angular was not discussed. Angular will get its due in a future post.

#### Run the application

Once the npm packages are downloaded for the project we can hit F5 and see what happens. the TypeScript files are compiled into JavaScript and we get the following in a browser:

Success! We have a decent starting point, but we have quite a bit ahead. This is a good a place to take a breather.

### Conclusion

Today we got all the necessary tools to get a simple node/express application written in TypeScript running in a Windows environment, along with having git and MongoDB installed. In part 2, I will attempt to hook up my application with MongoDB and in part 3, get angular working on the client-side.

Cheers!