
> This tutorial series explains how to build web applications with the MEAN stack. The MEAN stack is [MongoDB](https://www.mongodb.com/), [Express.js](http://expressjs.com/), [Angular](https://angular.io/), and [Node.js](https://nodejs.org/en/). This stack allows to write web applications, where JavaScript can be used both for the client and the server.
> In this tutorial a simple web application to manage portfolios of cryptocurrencies such as Bitcoin or Ethereum will be built.
#### What will I learn?
In this part of the tutorial series
- you will learn to setup your development environment with everything needed to use the MEAN stack,
- you will learn to create and maintain a Node.js project with npm,
- and you will learn to create a basic framework for the server backend of a web application with Node.js and Express.js.
#### Requirements
For this part of the tutorial you need the following background knowledge:
- Working with the command line
- Experience in JavaScript
#### Difficulty
Intermediate.
#### Tutorial contents
In this part of the series, the tutorial focuses on how to setup the development stack for MEAN web applications on Windows. It also shows how to setup the basic framework for the web application that will be built throughout this series.
##### macOS or Linux
Although the installation section of this tutorial is focused on Windows, most parts can be applied to macOS and Linux. Visual Studio Code comes for these operating systems as well. On macOS I recommend to use `brew` to install Node.js and MongoDB, on Linux you should be able to install them with `apt-get` on recent Debian based distributions.
##### Install Visual Studio Code
You can use the editor of your choice to develop MEAN applications, but I found Visual Studio Code to be the best IDE to get started with Node.js development. I tried Atom first, but I couldn't get debugging working on Windows. Then I installed Visual Studio Code and debugging worked out of the box and I was happy.
Get it at https://code.visualstudio.com/ and be sure to pick to 64 Bit version unless you really are stuck with a 32 Bit installation of Windows (pick up a new machine then).
After you got Visual Studio Code installed and running, you should install the "Prettier" extension for automatic code formatting. To do so, press `Ctrl+Shift+x` and enter Prettier. Now select "Prettier - Code formatter" and install it (Be sure to reload). Next press `Ctrl+,` to open your settings file and add the following lines to enable format on save for JavaScript and TypeScript Documents:
"[typescript]": {
"editor.formatOnSave": true
},
"[javascript]": {
"editor.formatOnSave": true
}
Verify that everything works correctly by creating a new document `app.js` in Visual Studio Code and entering some ill-formated code like:
console. log ( "hello world" ) ;
Save the document with `Ctrl+s` and it should atomatically change to
console.log("hello world");
##### Install Node.js
The first component to install is Node.js, the JavaScript Runtime for the server. It contains the V8 Engine from the Chrome Browser to execute JavaScript outside the browser and comes with `npm` a powerful package manager and the door to an ecosystem of currently more than 350.000 packages, that can be used in your projects.
There is not much to say on the Node.js installation itself, grab the newest version at https://nodejs.org and install it.
Verify that everything runs correctly by going back to your `app.js` document in Visual Studio Code and hit F5 to start it with the Node.js debugger. The debugging console should pop open and you should see some output like

##### Install MongoDB
MongoDB is a popular NoSQL database, i.e. it doesn't store its data in tables or relations which can be queried with the SQL language. Instead it stores collections of documents which provides an easier mapping of JavaScript objects to this database. This makes working with such databases easier, but comes at the cost of a bit of efficiency.
Go to the download center at https://www.mongodb.com/download-center select "Community Server" and download the current stable release for Windows. You may choose a custom installation directory during installation, but I assume it was installed to `C:\Program Files\MongoDB\Server\3.6\`.
MongoDB requires a data directory where it stores all data. If you don't have a default location for such directories, I'd suggest to store it in `%USERPROFILE%\data\db`. Create the directory in the Windows command prompt with
md %USERPROFILE%\data\db
You can now start the MongoDB demon, which was installed to "C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe". Open a new command prompt and enter
"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --dbpath %USERPROFILE%\data\db
Be aware that this way MongoDB does not run as a service and you need to keep this command prompt open and mongod.exe running while you are working with it. This has the advantage, that MongoDB does not run always and consume resources on your system, but only if you need it. Of course it is possible to install MongoDB as a service. If you are interested in this, look it up in the MongoDB documentation.
##### Create the application framework
Now, go back to Visual Studio Code to verify that everything works as expected.
To do so, we setup a project with npm, create a git repository, install two of the main `npm` packages and create a small Node.js application using them.
`npm` is the goto package manager for Node.js with more than 350.000 packets available. It is used to create and manage Node.js projects and its dependencies.
To create a new project, make a new folder for a project, enter it and execute
npm init
npm will ask some questions on the project, such as name and version. Everything can be changed later, so it is fine to accept the defaults. As a result npm creates a file named `package.json` in the current directory with approximatly the following contents:
{
"name": "mean_tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
}
Most developers change the entry point "main" to "app.js", so I recommend to this now, as well.
Next, install the two fundamental packages for our project: [mongoose](http://mongoosejs.com/) and [Express](http://expressjs.com/). mongoose is used to establish a connection with MongoDB and to map JavaScript objects to MongoDB documents. Express is the server-side web framework for Node.js that manages incoming GET/POST requests and dispatches them to JavaScript functions. Express itself is pretty simple but it can be extended with various middlewares, which makes it very powerful and adaptable to many use cases.
To install a package, npm is called with
npm install package_name@version --save
The @version part is optional. `npm` uses sematic versioning, i.e. three numbers separated by two dots, where the first number denotes the major version, the second number the minor version, and the last number the bugfix level. Since the Node.js ecosystem is under persistent change, I will specify the versions, that are current at the time this tutorial is written. This ensures, that the code shown in this tutorial will still work, even if newer versions of these packages introduce breaking changes.
The parameter `--save` tells npm to add the installed package in `package.json` as dependency. This is very useful, because this way all dependencies of an application can be installed only having `package.json` with `npm install`. So lets install these two packages:
npm install express@4 --save
npm install mongoose@5 --save
A new subfolder `node_modules` has been created and the following lines have been added to `package.json`:
"dependencies": {
"express": "^4.16.2",
"mongoose": "^5.0.2"
}
The actual versions in your `package.json` may slightly differ, as newer versions of these packages get released. The caret in front of the version fixes the major version. E.g. for express, in this case the newest 4.x.x versions greater than 4.16.2 will be installed, but no 5.x.x versions. This is usally fine, since only major updates should introduce breaking changes (such as removed or renamed functions).
##### Setup a git repository
This step is completely optional, but for actual development projects a git repository should be setup now (at the latest). So intialize a new repository with
git init
Before adding all files, create a '.gitignore' and initialize it with
node_modules/
since it is unnecessary to store the dependencies, if we can get them with `npm install`. It is recommended to add `package-lock.json` to version control. Add and commit everything with
git add *.js
git add *.json
git add .gitignore
git commit -m "Initial commit."
##### Create the framework of the server
To start coding the server, create a new file `app.js` in the folder next to `package.json`. First import the two new modules with `require()`. Node.js automatically finds packages installed in node_modules without having to specify the full path.
"use strict";
const express = require("express");
const mongoose = require("mongoose");
Setup the connection to the running MongoDB instance by calling `connect()` on the `mongoose` object with the URL of the database. Two callbacks are registered with the `mongoose.connection` object. One that is called if the connection could be established, and a second one, that is called if an error occurs.
const mongodb_database = "mongodb://localhost:27017/mean_stack_setup";
mongoose.connect(mongodb_database);
// register a callback for a successful connection
mongoose.connection.on("connected", () => {
console.log("Connected to database " + mongodb_database);
});
// register a callback for MongoDB errors
mongoose.connection.on("error", err => {
console.log("Database error: " + err);
});
The following part creates a new Express application object and starts it. To start it, the `listen` function must be called with a port (for the web server) and a callback function, which is called as soon as the server is up and running.
const app = express();
const port = 3000;
app.listen(port, () => {
console.log("Server started on port " + port);
});
Finally, create the first route. Basically this registers a JavaScript function, which is called when ever a specific address or endpoint is requested from the web server. In this case the main route "/" is set to a function which solely sends the string "Hello World" back.
const app = express();
const port = 3000;
app.listen(port, () => {
console.log("Server started on port " + port);
});
Press F5 or enter `node app.js` in the Terminal window to execute it. If everything was installed as expected, the output should look like
app.use("/", (req, res, next) => {
res.send("Hello World");
});
Now go to your browser and access the URL http://localhost:3000/. The string "Hello World" appears in the browser window.

This concludes the first part of this tutorial series. You have created a web server that connects to a MongoDB database.
##### Wait, what about Angular?
Yes, Angular is an essential part of the MEAN stack, but the first parts of this tutorial will focus on the server side portion of the example application and hence Angular hasn't been installed at all, yet.
##### Example code on Github
The code for this part of the tutorial can be found on [Github](https://github.com/nafest/mean_tutorial/tree/master/lesson1).
#### What's next?
In the next part I will start with extending the backend of our application and implement basic user management including registration and authentication.
<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@nafestw/mean-tutorial-part-1-get-started-with-the-mean-development-stack">Utopian.io - Rewarding Open Source Contributors</a></em><hr/>