create account

MEAN Tutorial Part 1 - Get started with the MEAN development stack by nafestw

View this thread on: hive.blogpeakd.comecency.com
· @nafestw · (edited)
$20.03
MEAN Tutorial Part 1 - Get started with the MEAN development stack
![logo.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1517341607/ldgbpdt41n59ze4cctsn.png)
> 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

![debug_console.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1517341831/ffp8xshgyoohybi3zyja.png)

##### 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.

![browser.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1517342522/gnhjhjcuigxqvrnlcp8z.png)

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/>
👍  , , , , ,
properties (23)
authornafestw
permlinkmean-tutorial-part-1-get-started-with-the-mean-development-stack
categoryutopian-io
json_metadata{"community":"utopian","app":"steemit/0.1","format":"markdown","repository":{"id":27193779,"name":"node","full_name":"nodejs/node","html_url":"https://github.com/nodejs/node","fork":false,"owner":{"login":"nodejs"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","nodejs","mongodb","angular","javascript"],"users":["version"],"links":["https://www.mongodb.com/","http://expressjs.com/","https://angular.io/","https://nodejs.org/en/","https://code.visualstudio.com/","https://nodejs.org","https://www.mongodb.com/download-center","http://mongoosejs.com/","http://localhost:3000/","https://github.com/nafest/mean_tutorial/tree/master/lesson1","https://utopian.io/utopian-io/@nafestw/mean-tutorial-part-1-get-started-with-the-mean-development-stack"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1517341607/ldgbpdt41n59ze4cctsn.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1517341831/ffp8xshgyoohybi3zyja.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1517342522/gnhjhjcuigxqvrnlcp8z.png"],"moderator":{"account":"shreyasgune","time":"2018-01-31T10:17:29.551Z","reviewed":true,"pending":false,"flagged":false}}
created2018-01-30 20:19:15
last_update2018-01-31 19:50:33
depth0
children3
last_payout2018-02-06 20:19:15
cashout_time1969-12-31 23:59:59
total_payout_value13.882 HBD
curator_payout_value6.152 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12,529
author_reputation2,113,027,036,393
root_title"MEAN Tutorial Part 1 - Get started with the MEAN development stack"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id33,655,458
net_rshares3,708,725,688,387
author_curate_reward""
vote details (6)
@shreyasgune ·
$0.67
Thank you for the contribution. It has been approved.

* Please put all your code in code box instead of pics. This also helps us to check plagiarism. 
* Not following instructions will lead to immediate rejection.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
👍  ,
properties (23)
authorshreyasgune
permlinkre-nafestw-mean-tutorial-part-1-get-started-with-the-mean-development-stack-20180131t101801624z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-31 10:18:21
last_update2018-01-31 10:18:21
depth1
children1
last_payout2018-02-07 10:18:21
cashout_time1969-12-31 23:59:59
total_payout_value0.504 HBD
curator_payout_value0.163 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length333
author_reputation4,924,803,411,962
root_title"MEAN Tutorial Part 1 - Get started with the MEAN development stack"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id33,821,187
net_rshares106,984,062,122
author_curate_reward""
vote details (2)
@nafestw ·
Hi @shreyasgune, thanks for the approval for my first submission.
I removed the code screenshots and put the code back in place. I used the screenshots to have proper syntax highlighting. Are there any plans to bring syntax highlighting to utopian.io? If not, this could be something, I could work on. The CommonMark spec already has a way to specify the language of a code block (-> http://spec.commonmark.org/0.27/#fenced-code-blocks)
properties (22)
authornafestw
permlinkre-shreyasgune-re-nafestw-mean-tutorial-part-1-get-started-with-the-mean-development-stack-20180131t114231211z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-31 11:42:30
last_update2018-01-31 11:42:30
depth2
children0
last_payout2018-02-07 11:42:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length436
author_reputation2,113,027,036,393
root_title"MEAN Tutorial Part 1 - Get started with the MEAN development stack"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id33,837,703
net_rshares0
@utopian-io ·
### Hey @nafestw I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- This is your first accepted contribution here in Utopian. Welcome!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-nafestw-mean-tutorial-part-1-get-started-with-the-mean-development-stack-20180131t132554310z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-31 13:25:54
last_update2018-01-31 13:25:54
depth1
children0
last_payout2018-02-07 13:25:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,524
author_reputation152,955,367,999,756
root_title"MEAN Tutorial Part 1 - Get started with the MEAN development stack"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id33,859,296
net_rshares0