Initial project setup of a MEAN stack
Tags: angular, node, mongodb, webdev
Published: 2020-06-27 18:05:36

This blog post was originally published on [ToubiDev](ToubiDev.ch)

# MEAN Stack
The MEAN stack is a collection of technologies that allow you to write the application with JavaScript. On the client side as well as on the server side. Furthermore, the entire stack is free and open-source. All frameworks work very well together. The MEAN stack is very well suited to create a robust and dynamic web application.

The MEAN stack consists of the following four components:

* MongoDB – NoSQL database which stores data in JSON format
* Express.js – Web Framework which runs with Node.js
* Angular – Frontend Framework written with TypeScript
* Node.js – JavaScript Runtime

# Prerequisites
Before we can start the project, the following two things must be installed:

* [MongoDB](https://docs.mongodb.com/manual/installation/)
* [Node.js](https://nodejs.org/en/download/)

# Server
To initialize the server, we create a new folder called server in the root directory. In this directory we execute `npm init`.

![npm init](https://dev-to-uploads.s3.amazonaws.com/i/28x7obtzsng6hnjjiy33.jpg)

With this command we create a package.json file. This file manages all local npm packages needed for the project. It also contains the metadata of the project, like the name or version.

For the server we still need some dependencies. We install them as follows:

`npm install express body-parser mongoose nodemon --save`

As already mentioned, “express” is our web framework for the server. “body-parser” is a middleware application and parses the request body. “mongoose” is in object modeling tool for MongoDB. It also allows us to interact with the database. “nodemon” is a useful tool to show live changes. It waits for changes in the code and restarts the server automatically. However, nodemon should only be used in development.

Now we can start configuring the server. We have already created the directory server. This will contain all controllers, models and routes. In the directory server we now create the file base.route.js in the subdirectory called routes:

```javascript
const express = require('express');
const router = express.Router();

router.get('/', function (req, res) {
    res.send('API works!');
});

module.exports = router;
```

Not much is happening here yet. We just added a route which returns “API works!” when called. To call this route, we need to be able to start the server first. For this we create a file called server.js in the directory server:

```javascript
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const mongoose = require('mongoose');
const dbConfig = require('./config/database.config');
const routes = require('./routes/base.route');

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

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

mongoose.connect(dbConfig.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
}).then(() => {
    console.log("Successfully connected to the database");
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...', err);
    process.exit();
});

const port = process.env.PORT || '8000';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, function () {
    console.info(`Server is up and running on port ${port}`)
});
```

As already mentioned, the first thing to insert is the “body parser”. Then we configure the route so that our API runs under /api. Finally we connect to the database which is defined in the file config/database.config.js:

```javascript
module.exports = {
    url: 'mongodb://localhost:27017/mean_stack'
}
```

MongoDB will automatically create the database, in this case “mean_stack”.

To start the server now, we can run `node server.js`. But we have installed nodemon so that we don’t have to restart the server after every change. To use Nodemon, we have to modify the file package.json. We add the following under scripts:

`"start": "nodemon server.js"`

If we run `npm start` now, the server will start and is available at http://localhost:8000. And at http://localhost:8000/api you can see the message “API works!” from our API.

Now the folder structure should look like this:

```
\---server
    |   package-lock.json
    |   package.json
    |   server.js
    |   
    +---config
    |       database.config.js
    |       
    \---routes
            base.route.js
```

# Angular App

First we install the Angular CLI tool:

`npm install -g @angular/cli`

With this tool the creation of the Angular application is made very easy. It only needs the command `ng new app`

![ng new app](https://dev-to-uploads.s3.amazonaws.com/i/pbyzilvqhpy783dud89p.jpg)

Below the created directory app is now our Angular application installed. To start it we execute the following command:

`ng serve`

The Angular application is now running at http://localhost:4200.

![angular app](https://dev-to-uploads.s3.amazonaws.com/i/bchktjjffaiaqauvxil0.jpg)

The folder structure of the Angular application should look like this:

```
+---app
|   |   .editorconfig
|   |   .gitignore
|   |   angular.json
|   |   browserslist
|   |   karma.conf.js
|   |   package-lock.json
|   |   package.json
|   |   README.md
|   |   tsconfig.app.json
|   |   tsconfig.json
|   |   tsconfig.spec.json
|   |   tslint.json
|   |   
|   +---e2e
|   |   |   protractor.conf.js
|   |   |   tsconfig.json
|   |   |   
|   |   \---src
|   |           app.e2e-spec.ts
|   |           app.po.ts
|   |           
|   \---src
|       |   favicon.ico
|       |   index.html
|       |   main.ts
|       |   polyfills.ts
|       |   styles.css
|       |   test.ts
|       |   
|       +---app
|       |       app.component.css
|       |       app.component.html
|       |       app.component.spec.ts
|       |       app.component.ts
|       |       app.module.ts
|       |       
|       +---assets
|       |       .gitkeep
|       |       
|       \---environments
|               environment.prod.ts
|               environment.ts
|   
```

You can find the code in the following Repository: {% github felberto/mean-stack-initial-setup %}