Now that we have a database (see Let's Build a Full-Stack App Using the MERN Stack! Part 1: Mongo DB), it's time to build the backend! In this tutorial, we’ll set up a simple backend using Node.js, Express, and MongoDB. By the end, you’ll have a working API that you can interact with.
Step 1: Setting Up the Backend
1. Create the Backend Folder
First, create a new folder for your backend and open it in your code editor:
mkdir backend
cd backend
code .
2. Initialize a Node.js Project
Run the following command to initialize a new Node.js project: npm init -y
3. Install Dependencies
We need to install some essential packages for our backend: npm install express mongoose cors dotenv
- express – Handles routing and HTTP requests.
- mongoose – Connects and interacts with MongoDB.
- cors – Allows cross-origin requests (important for frontend-backend communication).
- dotenv – Manages environment variables like database connection strings.
Step 2: Creating the Server
1. Create an index.js File
Inside the backend folder, create a new file named index.js and add the following code:
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const Thing = require('./models/Thing');
require("dotenv").config();
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
// MongoDB Connection
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB Connected!"))
.catch((err) => console.log(err));
// Routes
app.get("/", (req, res) => {
res.send("API running!");
});
// Create a thing
app.post('/things', async (req, res) => {
const thing = new Thing(req.body);
await thing.save();
res.status(201).send(thing);
});
// Get all things
app.get('/things', async (req, res) => {
const things = await Thing.find();
res.send(things);
});
// Update a thing
app.put('/things/:id', async (req, res) => {
const thing = await Thing.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(thing);
});
// Delete a thing
app.delete('/things/:id', async (req, res) => {
await Thing.findByIdAndDelete(req.params.id);
res.status(204).send();
});
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
2. Set Up Environment Variables
Create a .env file in the backend folder and add your MongoDB connection string: MONGO_URI=mongodb://watson:watson@localhost:27000/
Step 3: Creating a Model
Inside the backend folder, create a new folder called models.
Then, inside the models folder, create a new file called Thing.js and add the following code:
const mongoose = require("mongoose");
const ThingSchema = new mongoose.Schema(
{
title: { type: String, required: true },
description: { type: String, required: false },
},
{ timestamps: true }
);
module.exports = mongoose.model("Thing", ThingSchema);
This defines a simple Thing model with a title and description.
Step 4: Running the Backend
Now, let’s start the backend server: node index.js
If everything is set up correctly, you should see:
MongoDB Connected!
Server running on port 5000
Step 5: Testing the API
1. Install Postman (if you haven't already)
Download Postman and install it to test your API.
2. Create Some Things
Open Postman.
Set the request type to POST.
Enter http://localhost:5000/things.
Go to the Body tab, select raw, and choose JSON.
Add the following JSON data:
{
"title": "First Thing",
"description": "This is a test thing"
}
Click Send to create a new Thing.
3. Get Some Things!
Change the request type to GET.
Enter http://localhost:5000/things.
Click Send to retrieve all Things.
Conclusion
🎉 Whoohoo! You now have a working backend service with Node.js, Express, MongoDB, and Mongoose. This is a great foundation for building a full-stack application. In the next steps, you can extend this API with more endpoints, authentication, and validation.
Let me know if you have any questions! 🚀
Top comments (0)