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.
By the end of this post, you will be able to:
Before we begin, make sure you have the following installed on your system:
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-project
cd mean-stack-project
npm init -y
This command creates a package.json
file, which will store all your project’s dependencies and metadata.
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.
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}`);
});
/
) and responds with a simple message.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.
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
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:
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}`);
});
mongodb://localhost:27017/meanstackdb
(you can replace this with your MongoDB Atlas URL if using cloud MongoDB).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/models
touch 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;
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/controllers
touch 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/routes
touch 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);
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
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:
Let us know in the comments if you have any questions or need further assistance!
Comments are closed