Performing CRUD (Create, Read, Update, Delete) operations with Mongoose in a Node.js application is straightforward. Mongoose is an ODM (Object Data Modeling) library that simplifies the interaction with MongoDB by using schemas to define data models. Here’s a guide on how to implement CRUD operations with Mongoose in a Node.js application.
Assuming you have already set up MongoDB and Node.js, let’s begin by installing Mongoose and Express if you haven’t done so already:
npm install express mongoose
In Mongoose, a model is an abstraction for interacting with a MongoDB collection. It defines the structure of the documents within a collection and provides a range of methods for querying and modifying the database.
Let’s create a User
model as an example. Create a userModel.js
file:
javascript
Copy code
// userModel.js const mongoose = require('mongoose'); // Define the schema for the 'User' collection const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: { type: Number, required: true } }); // Create a model for the 'User' collection const User = mongoose.model('User', userSchema); module.exports = User;
server.js
In server.js
, we’ll set up the connection to MongoDB and create the routes for CRUD operations.
javascript
Copy code
const express = require('express'); const mongoose = require('mongoose'); const User = require('./userModel'); // Initialize the Express app const app = express(); app.use(express.json()); // Middleware to parse JSON requests // MongoDB URI (local or MongoDB Atlas) const mongoURI = 'mongodb://localhost:27017/myapp'; // For local MongoDB // const mongoURI = 'mongodb+srv://<username>:<password>@cluster.mongodb.net/myapp'; // For MongoDB Atlas // Connect to MongoDB mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log('Connected to MongoDB...')) .catch((err) => console.error('MongoDB connection error:', err)); // Route to check if server is running app.get('/', (req, res) => { res.send('MongoDB and Node.js CRUD API'); }); // Start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}...`); });
Now, let’s implement the CRUD routes for creating, reading, updating, and deleting users in MongoDB.
To create a new user, we’ll define a route that accepts a JSON payload and saves a new document to the User
collection.
javascript
Copy code
// Create a new user app.post('/users', async (req, res) => { const { name, email, age } = req.body; try { const newUser = new User({ name, email, age }); await newUser.save(); res.status(201).json(newUser); // Respond with the created user } catch (err) { res.status(400).send('Error creating user: ' + err.message); } });
To retrieve users, we can fetch all users or find a specific user by their id
.
javascript
Copy code
// Get all users app.get('/users', async (req, res) => { try { const users = await User.find(); // Find all users res.status(200).json(users); // Respond with the users array } catch (err) { res.status(500).send('Error fetching users: ' + err.message); } });
javascript
Copy code
// Get user by ID app.get('/users/:id', async (req, res) => { const { id } = req.params; try { const user = await User.findById(id); // Find user by ID if (!user) return res.status(404).send('User not found'); res.status(200).json(user); // Respond with the found user } catch (err) { res.status(500).send('Error fetching user: ' + err.message); } });
To update a user’s details, we use the findByIdAndUpdate()
method. This method finds the document by its ID and updates it with the new data.
javascript
Copy code
// Update user by ID app.put('/users/:id', async (req, res) => { const { id } = req.params; const { name, email, age } = req.body; try { const updatedUser = await User.findByIdAndUpdate( id, { name, email, age }, { new: true } // Return the updated document ); if (!updatedUser) return res.status(404).send('User not found'); res.status(200).json(updatedUser); // Respond with the updated user } catch (err) { res.status(400).send('Error updating user: ' + err.message); } });
To delete a user, we use the findByIdAndDelete()
method, which removes a document by its ID.
javascript
Copy code
// Delete user by ID app.delete('/users/:id', async (req, res) => { const { id } = req.params; try { const deletedUser = await User.findByIdAndDelete(id); if (!deletedUser) return res.status(404).send('User not found'); res.status(200).send('User deleted'); } catch (err) { res.status(500).send('Error deleting user: ' + err.message); } });
After running your Node.js app (node server.js
), you can use tools like Postman or cURL to test the CRUD operations.
POST http://localhost:3000/users
{ "name": "John Doe", "email": "john.doe@example.com", "age": 30 }
GET http://localhost:3000/users
GET http://localhost:3000/users/{id}
PUT http://localhost:3000/users/{id}
{ "name": "John Doe Updated", "email": "john.doe.updated@example.com", "age": 31 }
DELETE http://localhost:3000/users/{id}
While this example covers basic CRUD operations, Mongoose provides built-in validation capabilities that you can utilize to enforce data integrity.
For example, you can add validation rules to the schema:
javascript
Copy code
const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true, match: /.+\@.+\..+/ }, age: { type: Number, required: true, min: 18 } });
This ensures:
name
field is required.email
field is unique and must match a valid email format.age
field is required and must be at least 18.With this setup, you now have a fully functioning CRUD API using Express and Mongoose to manage User documents in MongoDB. You can extend this further by adding more routes, implementing advanced queries, using middleware for authentication, and adding error handling logic. Mongoose’s ability to define schemas and validate data makes it easy to interact with MongoDB in a structured and efficient manner.