CRUD with Mongoose: A Comprehensive Node.js Tutorial šŸŽÆ

beginner
13 min

CRUD with Mongoose: A Comprehensive Node.js Tutorial šŸŽÆ

Welcome to our deep dive into CRUD (Create, Read, Update, Delete) operations using Mongoose in Node.js! By the end of this tutorial, you'll have a strong foundation for building dynamic web applications with Node.js and MongoDB.

Let's start by understanding what each CRUD operation means:

  • Create: Adding new data to a database collection.
  • Read: Retrieving data from a database collection.
  • Update: Modifying existing data in a database collection.
  • Delete: Removing data from a database collection.

Prerequisites šŸ“

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

  • Node.js (version 14 or higher)
  • MongoDB (we'll use the built-in MongoDB Atlas server)

Setting Up the Project āœ…

  1. Create a new directory for your project:
bash
mkdir my-project && cd my-project
  1. Initialize a new Node.js project:
bash
npm init -y
  1. Install Express and Mongoose:
bash
npm install express mongoose

Connecting to MongoDB šŸ’”

First, let's set up a connection to our MongoDB database using Mongoose. Create a new file called db.js:

javascript
// db.js const mongoose = require('mongoose'); mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }) .then(() => console.log('MongoDB connected...')) .catch((err) => console.error(err));

šŸ“ Note: Replace <username> and <password> with your MongoDB Atlas credentials.

Creating a Schema šŸ’”

Next, let's create a schema for our data model. Create a new file called user.js:

javascript
// user.js const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: Number, isAdmin: Boolean, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('User', UserSchema);

Performing CRUD Operations šŸ’”

Now, let's create routes for each CRUD operation. Create a new file called index.js:

javascript
// index.js const express = require('express'); const router = express.Router(); const User = require('./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 }); } }); // READ: Get a single user router.get('/users/:id', getUser, (req, res) => { res.json(res.user); }); // UPDATE: Update a user router.patch('/users/:id', getUser, async (req, res) => { if (req.body.isAdmin) { res.user.isAdmin = req.body.isAdmin; } try { await res.user.save(); res.json(res.user); } catch (error) { res.status(400).json({ message: error.message }); } }); // DELETE: Delete a user router.delete('/users/:id', getUser, async (req, res) => { try { await res.user.remove(); res.json({ message: 'User deleted successfully' }); } catch (error) { res.status(500).json({ message: error.message }); } }); async function getUser(req, res, next) { let user; try { user = await User.findById(req.params.id); if (!user) { return res.status(404).json({ message: 'User not found' }); } } catch (error) { return res.status(500).json({ message: error.message }); } res.user = user; next(); } module.exports = router;

Setting Up Express Routes šŸ’”

Finally, let's set up our Express application and use our routes. Create a new file called app.js:

javascript
// app.js const express = require('express'); const mongoose = require('mongoose'); const userRoutes = require('./routes/index'); const app = express(); const port = 3000; app.use(express.json()); app.use('/api/users', userRoutes); mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }) .then(() => app.listen(port, () => console.log(`Server running on port ${port}`))) .catch((err) => console.error(err));

šŸ’” Pro Tip: Replace <username> and <password> with your MongoDB Atlas credentials in both db.js and app.js.

Testing Our Application šŸ’”

Now that our application is set up, let's test our routes using a tool like Postman or cURL.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What does CRUD stand for in the context of database operations?

That's it for our CRUD with Mongoose tutorial! You're now ready to create, read, update, and delete data using Node.js, Express, and MongoDB. Keep exploring and building! šŸŽ‰