# Node.js Application Setup Procedure

Find the Github Repo [here](https://github.com/Nate-Agbara/wallet-system.git)

### Project Setup

* Download and install node from [https://nodejs.org/en/download/](https://nodejs.org/en/download/). This will also install npm which is a package manager for node.
    
* Open a new terminal on your machine or from your code editor of choice and change directory (cd) to your workspace.
    
* Create a new directory that is the name of your project and cd into the newly created project directory
    
* Create the package.json file for the project: do `npm init`. This will ask for some details, but they're all optional
    
* Now install express next. simply do `npm i express`
    
* Next, we need to install babel. Babel is a Javascript compiler that compiles the latest Javascript syntaxes for the browser to understand. To install babel run `npm i --save-dev @babel/core @babe/cli @babel/node @babel/preset-env` we are saving it to dev because it is a dev dependency
    
* Next, install nodemon and body-parser. do `npm i nodemon body-parser`
    
* When the installation of babel and nodemon is done, open your project in the editor. In the root project, create a file called `.babelrc`, inside this file, you will create an object and pass the presets. You will have something like this:
    
    ```json
    { "presets": [ "@babel/preset-env" ] }
    ```
    

Your project setup is complete.

### Initial Server Setup

Change the script in `package.json` file so that nodemon picks the index file when the `npm start` command is executed set it to:

```json
"scripts": {
    "start": "nodemon ./index.js --exec babel-node"
  },
```

Next, we need to create the index.js file which is the main entry point of the application. Open the created file and type the following:

```javascript
import express from "express";

const app = express(); const PORT = 3000;

app.get('/', (req, res) => res.send(Node and express server is running on port ${PORT}) );

app.listen(PORT, () => console.log(Your server is running on port ${PORT}) );
```

first line imports express from the express package, the second line assigns a variable to the express server, the third line defines a port the server should run on. This can be any free port on your machine. The fourth line defines a default route we can call on our browser or any other client like postman just to test whether the express server is running when it is started with `npm start` command. The fifth line is a console message to show our application server is running.

### File Structure

In the root of your project, create an src directory. Inside this directory, create three directories, controllers, models and routes respectively.

**controller**

This directory holds the controllers for all the objects in your application.

**model**

This is where the database models for your application reside

**routes**

Here, all the URL routes in your application are defined.

### Database Setup

**MongoDB Setup**

* Go to [https://www.mongodb.com/](https://www.mongodb.com/) and under the products tab, click on community server and proceed to download
    
* Install mongoose: Mongoose is a node.js library for MongoDB database. run `npm install mongoose`
    
* Go to the index.js file and setup the mongoose connection as well as the body-parser
    
* ```javascript
    //mongoose connection
    mongoose.set('strictQuery', true);
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://127.0.0.1/walletdb', {
        useNewUrlParser: true
    });
    
    //bodyparser setup
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    ```
    
* Create a walletMode.js file in your project's models directory. In this file, you will define the object model (account model for this example)
    

```javascript
import mongoose from "mongoose";

const Schema = mongoose.Schema;

export const AccountSchema = new Schema({
    firstName: {
        type: String,
        required: 'enter firstname'
    },
    lastName: {
        type: String,
        required: 'enter lastname'
    },
    email: {
        type: String
    },
    phone: {
        type: Number
    },
    created_date: {
        type: Date,
        default: Date.now()
    }
});
```

* Finally, create a walletController.js file in the controllers directory. Functions to do CRUD operations will be implemented here.
    
* ```javascript
    import mongoose from "mongoose";
    import { AccountSchema } from "../models/walletModel";
    
    const Account = mongoose.model('Account', AccountSchema);
    
    export const addNewAccount = (req, res) => {
        let newAccount = new Account(req.body);
    
        newAccount.save((err, account) => {
            if(err){
                res.send(err)
            }
            res.json(account)
        });
    };
    
    export const getAllAccounts = (req, res) => {
        Account.find({}, (err, account) => {
            if(err){
                res.send(err)
            }
            res.json(account)
        });
    };
    
    export const getAccountById = (req, res) => {
        Account.findById(req.params.accountId, (err, account) => {
            if(err){
                res.send(err)
            }
            res.json(account)
        });
    };
    
    export const updateAccountById = (req, res) => {
        Account.findOneAndUpdate({ _id: req.params.accountId}, req.body, { new: true }, (err, account) => {
            if(err){
                res.send(err)
            }
            res.json(account)
        });
    };
    
    export const deleteAccountById = (req, res) => {
        Account.remove({ _id: req.params.accountId}, (err) => {
            if(err){
                res.send(err)
            }
            res.json({message: 'successfully deleted account'})
        });
    };
    ```
    

Github Repo: [https://github.com/Nate-Agbara/wallet-system.git](https://github.com/Nate-Agbara/wallet-system.git)
