Post 3: MongoDB Basics – Creating and Managing Data in MERN
In Post 2, we set up the development environment for our MERN stack application. Now it’s time to dive deeper into MongoDB, understanding how to structure data, perform basic CRUD operations, and connect MongoDB with our Express server using Mongoose.
MongoDB is a NoSQL database that stores data in a JSON-like format, making it flexible for applications that need to handle varying data structures. In this post, we’ll walk through creating a MongoDB database, defining data models with Mongoose, and building simple API endpoints.
1. Getting Started with MongoDB and Mongoose
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js, providing a schema-based solution for structuring application data. Let’s start by defining a basic model.
Define a Simple Mongoose Model
In your backend
folder, create a models
folder and add a file for your model, like User.js
:
// backend/models/User.js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
module.exports = mongoose.model("User", userSchema);
This User
schema has three fields: name
, email
, and password
. By using this schema, Mongoose will automatically handle things like data validation and indexing.
2. Creating a MongoDB Database
-
Using MongoDB Atlas: Log in, create a cluster, and get the connection URI. Set this URI in your
.env
file asMONGO_URI
. -
Connecting to MongoDB: In
index.js
, connect to the database as shown below:
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.log("Error connecting to MongoDB:", err));
3. Building CRUD Operations
Now that MongoDB is connected, let’s create basic CRUD (Create, Read, Update, Delete) routes in Express to manage User
data.
Create API Routes
In backend
, create a routes
folder with userRoutes.js
:
// backend/routes/userRoutes.js
const express = require("express");
const router = express.Router();
const User = require("../models/User");
// CREATE - Add a new user
router.post("/users", async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// READ - Get all users
router.get("/users", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// UPDATE - Update a user by ID
router.put("/users/:id", async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(user);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// DELETE - Remove a user by ID
router.delete("/users/:id", async (req, res) => {
try {
await User.findByIdAndDelete(req.params.id);
res.json({ message: "User deleted" });
} catch (error) {
res.status(500).json({ message: error.message });
}
});
module.exports = router;
Integrate Routes into the Server
Add these routes to your index.js
file:
const userRoutes = require("./routes/userRoutes");
app.use(express.json()); // Parse JSON requests
app.use("/api", userRoutes);
4. Testing the CRUD API
Using Postman or any API testing tool, you can test each route:
-
POST
/api/users
: Add a new user by sending JSON data (e.g.,{ "name": "Alice", "email": "alice@example.com", "password": "securepassword" }
). -
GET
/api/users
: Fetch a list of all users. -
PUT
/api/users/:id
: Update a user’s information by sending JSON data. -
DELETE
/api/users/:id
: Delete a user by specifying their ID.
What’s Next?
In Post 4, we’ll connect this backend with a React frontend and build out a simple interface to manage users visually. With our MongoDB setup, we’re one step closer to building a fully functional MERN app!
Top comments (0)