shape
shape

Setting Up Node.js and Express in Your MEAN Stack Project

  • Home
  • MEAN
  • Setting Up Node.js and Express in Your MEAN Stack Project

In this blog post, we will guide you through the process of setting up Node.js and Express in your MEAN stack project. MEAN stands for MongoDB, Express, Angular, and Node.js, which is a popular stack for building full-stack web applications. The primary goal of this tutorial is to help you configure the backend of your MEAN stack application using Node.js and Express.


What You Will Learn

By the end of this post, you will be able to:

  1. Set up Node.js and Express in your project.
  2. Create a basic Express server.
  3. Understand how to structure your MEAN stack backend.
  4. Integrate MongoDB with Express for handling database operations.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  1. Node.js: The runtime for executing JavaScript on the server.
  2. npm (Node Package Manager): Comes with Node.js, used for installing packages.
  3. MongoDB: A NoSQL database that stores data in a JSON-like format.
  4. A code editor: Such as Visual Studio Code.
  5. Git (optional): For version control.
Step 1: Initialize Your Project

The first step in setting up a MEAN stack project is to initialize your Node.js project. This can be done with the following command:

bash

 code

mkdir mean-stack-projectcd mean-stack-project

npm init -y

This command creates a package.json file, which will store all your project’s dependencies and metadata.

Step 2: Install Node.js and Express

Now that your project is initialized, it’s time to install the necessary packages. The key package we need is Express, a minimalist web framework for Node.js.

Run the following command to install Express:

bash

 code

npm install express

This will install Express and add it to the dependencies section of your package.json.

To make sure Express is installed, you can check your package.json file. You should see express listed as one of the dependencies.

Step 3: Create Your Basic Express Server

Now that Express is installed, let’s set up a basic Express server.

Create a new file called server.js:

bash

 code

touch server.js

Inside the server.js file, write the following code to create a basic server:

javascript

 code

const express = require(‘express’);const app = express();const port = 3000;

// Define a basic route

app.get(‘/’, (req, res) => {

  res.send(‘Hello, MEAN Stack!’);

});

// Start the server

app.listen(port, () => {

  console.log(`Server is running at http://localhost:${port}`);

});

What’s Happening Here?
  • express(): Creates an Express application instance.
  • app.get(): Defines a GET route that listens on the root URL (/) and responds with a simple message.
  • app.listen(): Starts the server on port 3000 and logs a message in the console once the server is up and running.

To run the server, use the following command in your terminal:

bash

 code

node server.js

If everything is set up correctly, you should see the message Server is running at http://localhost:3000. You can now visit this URL in your browser and see the “Hello, MEAN Stack!” message.


Step 4: Structuring Your Project

Now that you have a basic server running, it’s time to structure your project for scalability and ease of development. A typical MEAN stack project follows the Model-View-Controller (MVC) architecture, which helps separate concerns and keeps your code organized.

Here’s how you can structure your project:

php

 code

mean-stack-project/

├── node_modules/             # Installed dependencies

├── public/                   # Static files (e.g., Angular app)

├── src/                      # Source files for backend

│   ├── controllers/          # Controller logic for routes

│   ├── models/               # Database models (MongoDB schemas)

│   ├── routes/               # Express routes

│   └── server.js             # Main Express server file

├── package.json              # Project metadata and dependencies

└── README.md                 # Project documentation

Step 5: Setting Up MongoDB

Since you are building a MEAN stack application, MongoDB will be your database. Express will interact with MongoDB to handle data operations.

To get started with MongoDB:

  1. Install MongoDB on your machine (if not already installed).
  2. Create a database: You can use the MongoDB Atlas cloud service or run MongoDB locally.

We will use the Mongoose library to interact with MongoDB in a more structured way. Install Mongoose using npm:

bash

 code

npm install mongoose

Now, connect MongoDB to your Express app. Modify the server.js file to include MongoDB setup:

javascript

 code

const express = require(‘express’);const mongoose = require(‘mongoose’);const app = express();const port = 3000;

// MongoDB connection

mongoose.connect(‘mongodb://localhost:27017/meanstackdb’, {

  useNewUrlParser: true,

  useUnifiedTopology: true

})

.then(() => console.log(‘Connected to MongoDB’))

.catch(err => console.log(‘MongoDB connection error:’, err));

// Middleware

app.use(express.json());

// Define a basic route

app.get(‘/’, (req, res) => {

  res.send(‘Hello, MEAN Stack with MongoDB!’);

});

// Start the server

app.listen(port, () => {

  console.log(`Server is running at http://localhost:${port}`);

});

Explanation:
  • mongoose.connect(): Connects to MongoDB using the URI mongodb://localhost:27017/meanstackdb (you can replace this with your MongoDB Atlas URL if using cloud MongoDB).
  • express.json(): Middleware that parses incoming JSON requests.

Step 6: Create a Model

Now that MongoDB is connected, let’s create a simple model. A model represents the structure of a document in MongoDB.

Create a folder called models and inside it, create a file called user.js:

bash

 code

mkdir src/modelstouch src/models/user.js

Inside user.js, define a simple User schema:

javascript

 code

const mongoose = require(‘mongoose’);

const userSchema = new mongoose.Schema({

  name: {

    type: String,

    required: true

  },

  email: {

    type: String,

    required: true,

    unique: true

  },

  age: {

    type: Number,

    required: true

  }

});

const User = mongoose.model(‘User’, userSchema);module.exports = User;

Step 7: Create a Controller and Route

Next, create a controller to handle the logic for interacting with the User model. Create a folder called controllers and inside it, create a file called userController.js:

bash

 code

mkdir src/controllerstouch src/controllers/userController.js

Inside userController.js, add the following code to handle creating a new user:

javascript

 code

const User = require(‘../models/user’);

exports.createUser = (req, res) => {

  const { name, email, age } = req.body;

  const user = new User({

    name,

    email,

    age

  });

  user.save()

    .then(() => res.status(201).send(‘User created successfully’))

    .catch(err => res.status(400).send(‘Error creating user: ‘ + err));

};

Now, define a route to handle user creation. Create a folder called routes and inside it, create a file called userRoutes.js:

bash

 code

mkdir src/routestouch src/routes/userRoutes.js

Inside userRoutes.js, add the following code:

javascript

 code

const express = require(‘express’);const router = express.Router();const userController = require(‘../controllers/userController’);

router.post(‘/users’, userController.createUser);

module.exports = router;

Finally, import and use the route in server.js:

javascript

 code

const userRoutes = require(‘./src/routes/userRoutes’);

app.use(‘/api’, userRoutes);

Step 8: Test the API

Now that everything is set up, you can test your API using tools like Postman or Insomnia. Send a POST request to http://localhost:3000/api/users with the following JSON body:

json

 code

{

  “name”: “John Doe”,

  “email”: “johndoe@example.com”,

  “age”: 25}

If the user is successfully created, you should receive a response like:

sql

 code

User created successfully


Conclusion

Congratulations! You’ve successfully set up Node.js and Express in your MEAN stack project. You’ve learned how to create a basic Express server, structure your project using MVC, connect to MongoDB with Mongoose, and create an API to interact with your database.

Next steps:

  • Continue building out your Express routes and models.
  • Integrate Angular for the frontend to complete your MEAN stack application.
  • Learn about middleware for handling things like authentication and validation.

Let us know in the comments if you have any questions or need further assistance!

Additional learning resources:
  • C LANGUAGE COMPLETE COURSE – IN HINDI – Link
  • CYBER SECURITY TUTORIAL SERIES – Link
  • CODING FACTS SERIES – Link
  • SKILL DEVELOPMENT SERIES – Link
  • PYTHON PROGRAMMING QUIZ – Link
  • CODING INTERVIEW QUIZ – Link
  • JAVA PROGRAMMING QUIZ – Link
  • C PROGRAMMING QUIZ – Link

Comments are closed

0
    0
    Your Cart
    Your cart is emptyReturn to shop