Skip to content
FullStackDost Logo
  • All Courses
  • Blogs
  • Login
  • Register
  • All Courses
  • Blogs
  • Login
  • Register
  • Home
  • All Courses
  • Web development
  • MongoDB – (No-SQL)

MongoDB – (No-SQL)

Curriculum

  • 10 Sections
  • 31 Lessons
  • 10 Weeks
Expand all sectionsCollapse all sections
  • Introduction to MongoDB
    MongoDB is a NoSQL database that is designed for handling large volumes of unstructured or semi-structured data. Unlike traditional relational databases (RDBMS) that use tables and rows to organize data, MongoDB stores data in a flexible document-oriented format using JSON-like documents (BSON - Binary JSON). This makes it highly scalable, flexible, and performant for applications that need to handle varying types of data with complex structures.
    5
    • 1.1
      What is MongoDB?
    • 1.2
      Why MongoDB?
    • 1.3
      When to use MongoDB?
    • 1.4
      Key Features of MongoDB
    • 1.5
      Installing MongoDB
  • MongoDB Basic Operations
    MongoDB provides a rich set of basic operations for interacting with the database, including creating, reading, updating, and deleting data (often abbreviated as CRUD operations). Below are the basic operations that you can perform with MongoDB.
    2
    • 2.0
      Database and Collection Basics
    • 2.1
      CRUD Operations
  • Advanced Querying Techniques
    MongoDB offers a rich set of querying capabilities, and as you work with larger datasets and more complex application requirements, you’ll often need to use advanced querying techniques. These techniques help you optimize performance, execute sophisticated queries, and leverage MongoDB’s powerful indexing and aggregation features.
    4
    • 3.1
      Query Filters and Operators
    • 3.2
      Advanced Querying
    • 3.3
      Sorting and Limiting Results
    • 3.4
      Aggregation Framework
  • Data Modeling and Schema Design
    Data modeling and schema design are critical when using MongoDB (or any NoSQL database) to ensure efficient data storage, fast queries, and scalability. Unlike relational databases, MongoDB is schema-less, which means you are not required to define a fixed schema upfront. However, making the right design decisions from the beginning is essential for maintaining performance and avoid complications as your data grows.
    4
    • 4.1
      Data Modeling
    • 4.2
      Document Structure
    • 4.3
      Schema Design Patterns
    • 4.4
      MongoDB and Relationships
  • Indexing and Performance Optimization
    In MongoDB, indexing is a critical part of performance optimization. Without proper indexes, MongoDB has to scan every document in a collection to satisfy queries, which can be very inefficient for large datasets. Indexes are used to quickly locate data without scanning every document, making reads faster and more efficient.
    3
    • 5.0
      Creating Indexes
    • 5.1
      Using Text Search
    • 5.2
      Performance Optimization
  • Integrating MongoDB with a Web Application (Node.js)
    Integrating MongoDB with a web application built using Node.js is a common and powerful combination for building scalable and efficient web apps. MongoDB’s flexibility with JSON-like data and Node.js's asynchronous event-driven architecture work well together. In this guide, I'll walk you through the steps for integrating MongoDB with a Node.js web application, covering the essentials of setting up the connection, performing CRUD operations, and using popular libraries.
    3
    • 6.0
      Setting Up MongoDB with Node.js
    • 6.1
      CRUD Operations with Mongoose
    • 6.2
      Error Handling and Validation
  • Security in MongoDB
    Security is an essential aspect when working with MongoDB, especially when handling sensitive data in production environments. MongoDB provides a variety of security features to help protect your data against unauthorized access, injection attacks, and other vulnerabilities. Here’s a guide on securing MongoDB and your Node.js application when interacting with MongoDB.
    2
    • 7.0
      Authentication and Authorization
    • 7.1
      Data Encryption
  • Working with MongoDB in Production
    3
    • 8.0
      MongoDB Backup and Restore
    • 8.1
      MongoDB Scaling and Sharding
    • 8.2
      MongoDB Replication
  • Deploying and Monitoring MongoDB
    Working with MongoDB in a production environment requires careful planning, attention to detail, and best practices to ensure optimal performance, security, reliability, and scalability.
    3
    • 9.0
      Deploying MongoDB to Production
    • 9.1
      Monitoring and Management
    • 9.2
      Summary for MongoDB deployment on Production
  • Building a Web App with MongoDB (Final Project)
    Demo Project (OneStopShop)
    2
    • 10.0
      Building the Application
    • 10.1
      Final Project Features

CRUD Operations with Mongoose

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.

1. Install dependencies

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

2. Create the Mongoose Model

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;

3. Set Up Mongoose and Express in 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}...`); });

4. Create CRUD Operations

Now, let’s implement the CRUD routes for creating, reading, updating, and deleting users in MongoDB.

Create (POST)

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); } });

Read (GET)

To retrieve users, we can fetch all users or find a specific user by their id.

Get all users:

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); } });

Get user by ID:

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); } });

Update (PUT)

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); } });

Delete (DELETE)

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); } });

5. Test the CRUD API

After running your Node.js app (node server.js), you can use tools like Postman or cURL to test the CRUD operations.

Example of Test Cases:

  1. Create a User (POST):
    • URL: POST http://localhost:3000/users
    • Body (JSON):jsonCopy code{ "name": "John Doe", "email": "john.doe@example.com", "age": 30 }
  2. Get All Users (GET):
    • URL: GET http://localhost:3000/users
  3. Get User by ID (GET):
    • URL: GET http://localhost:3000/users/{id}
  4. Update User (PUT):
    • URL: PUT http://localhost:3000/users/{id}
    • Body (JSON):jsonCopy code{ "name": "John Doe Updated", "email": "john.doe.updated@example.com", "age": 31 }
  5. Delete User (DELETE):
    • URL: DELETE http://localhost:3000/users/{id}

6. Handle Validation & Errors

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:

  • The name field is required.
  • The email field is unique and must match a valid email format.
  • The age field is required and must be at least 18.

Conclusion

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.

Setting Up MongoDB with Node.js
Prev
Error Handling and Validation
Next

Copyright © 2025 FullStackDost. All Rights Reserved.

Theme by ILOVEWP