MongoDB - Performing CRUD Operations

MongoDB - Performing CRUD Operations

Performing CRUD Operations Using MongoDB

MongoDB is a powerful, document-oriented NoSQL database that stores data in a flexible, JSON-like format called BSON. It provides robust support for CRUD operationsβ€”Create, Read, Update, and Deleteβ€”which are the core operations required to manipulate and manage data in any database. In this guide, we will explore each of these operations in detail, using Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose makes working with MongoDB easier by providing a schema-based solution for modeling application data.

What is CRUD?

CRUD stands for:

  • Create: Insert data into the database
  • Read: Retrieve data from the database
  • Update: Modify existing data in the database
  • Delete: Remove data from the database

In a typical web application, these operations form the basis of interaction between the user and the backend database.

Setting Up the Environment

1. Installing MongoDB

Ensure that MongoDB is installed on your machine. You can download it from the official MongoDB website and follow the installation instructions for your operating system.

2. Setting Up a Node.js Project

mkdir mongo-crud-demo
cd mongo-crud-demo
npm init -y
npm install mongoose

This creates a Node.js project and installs Mongoose.

3. Connecting to MongoDB

Create a file called db.js for the MongoDB connection:

// db.js
const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/crud_demo', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('MongoDB connected');
}).catch(err => {
    console.error('Connection error:', err);
});

This script connects your Node.js application to the MongoDB database named "crud_demo".

Defining a Mongoose Schema

Before performing CRUD operations, we need to define a schema and model:

// models/User.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    age: Number
});

module.exports = mongoose.model('User', userSchema);

This defines a simple User model with fields: name, email, and age.

Performing CRUD Operations

Create Operation

To insert data into MongoDB, use the create or save method.

// create.js
const mongoose = require('mongoose');
const User = require('./models/User');
require('./db');

const createUser = async () => {
    const user = new User({
        name: 'Alice',
        email: 'alice@example.com',
        age: 25
    });

    await user.save();
    console.log('User Created:', user);
};

createUser();

This script adds a new user named Alice to the database.

Read Operation

To retrieve data from MongoDB, you can use methods like find, findOne, or findById.

// read.js
const mongoose = require('mongoose');
const User = require('./models/User');
require('./db');

const readUsers = async () => {
    const users = await User.find(); // Fetch all users
    console.log('All Users:', users);

    const oneUser = await User.findOne({ name: 'Alice' });
    console.log('Single User:', oneUser);
};

readUsers();

Here, all users are fetched, and also a single user named Alice is retrieved.

Update Operation

You can update existing records using updateOne, updateMany, or findByIdAndUpdate.

// update.js
const mongoose = require('mongoose');
const User = require('./models/User');
require('./db');

const updateUser = async () => {
    const updated = await User.findOneAndUpdate(
        { name: 'Alice' },
        { age: 26 },
        { new: true }
    );
    console.log('Updated User:', updated);
};

updateUser();

This updates Alice’s age to 26 and returns the modified document.

Delete Operation

To remove data from the database, use deleteOne, deleteMany, or findByIdAndDelete.

// delete.js
const mongoose = require('mongoose');
const User = require('./models/User');
require('./db');

const deleteUser = async () => {
    const result = await User.deleteOne({ name: 'Alice' });
    console.log('Deleted User:', result);
};

deleteUser();

This deletes the user whose name is Alice from the database.

Advanced CRUD with Query Options

Filtering with Queries

const usersOver25 = await User.find({ age: { $gt: 25 } });
console.log('Users over 25:', usersOver25);

Filters users whose age is greater than 25.

Sorting and Limiting

const sortedUsers = await User.find().sort({ age: -1 }).limit(3);
console.log('Top 3 oldest users:', sortedUsers);

Sorts by age in descending order and limits the result to 3 users.

Projections

const namesOnly = await User.find({}, 'name');
console.log('User Names:', namesOnly);

Retrieves only the names of all users.

Using async/await with Error Handling

const safeCreateUser = async () => {
    try {
        const user = new User({ name: 'Bob', email: 'bob@example.com', age: 30 });
        await user.save();
        console.log('User Saved:', user);
    } catch (error) {
        console.error('Error Saving User:', error.message);
    }
};

Always wrap your asynchronous code in try/catch blocks to handle exceptions gracefully.

Bulk Operations

Inserting Multiple Documents

const insertManyUsers = async () => {
    const users = [
        { name: 'John', email: 'john@example.com', age: 28 },
        { name: 'Jane', email: 'jane@example.com', age: 22 },
        { name: 'Jack', email: 'jack@example.com', age: 35 }
    ];
    await User.insertMany(users);
    console.log('Users inserted');
};

Allows multiple documents to be inserted at once.

Deleting Multiple Documents

const deleteAllYoungerThan25 = async () => {
    const result = await User.deleteMany({ age: { $lt: 25 } });
    console.log('Users Deleted:', result.deletedCount);
};

This deletes all users under the age of 25.

Populating Related Data

Suppose you have a reference to another schema. You can use the populate method to join documents.

// models/Post.js
const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: String,
    content: String,
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

module.exports = mongoose.model('Post', postSchema);
// fetchPosts.js
const Post = require('./models/Post');

const fetchPostsWithUsers = async () => {
    const posts = await Post.find().populate('author');
    console.log('Posts with Authors:', posts);
};

CRUD operations in MongoDB, especially with the help of Mongoose, are powerful and flexible. Using Mongoose allows you to interact with MongoDB through a structured, schema-based approach, making your application more maintainable and less error-prone.

To summarize, you’ve learned how to:

  • Set up a Node.js project with MongoDB
  • Define a Mongoose schema and model
  • Perform Create, Read, Update, and Delete operations
  • Use advanced query features like sorting, filtering, and projections
  • Use populate to relate documents

Mastering CRUD in MongoDB is essential for any developer working with modern full-stack applications. With the knowledge and code examples provided in this guide, you should be well-equipped to perform and implement effective database operations in your projects.

Beginner 5 Hours
MongoDB - Performing CRUD Operations

Performing CRUD Operations Using MongoDB

MongoDB is a powerful, document-oriented NoSQL database that stores data in a flexible, JSON-like format called BSON. It provides robust support for CRUD operations—Create, Read, Update, and Delete—which are the core operations required to manipulate and manage data in any database. In this guide, we will explore each of these operations in detail, using Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose makes working with MongoDB easier by providing a schema-based solution for modeling application data.

What is CRUD?

CRUD stands for:

  • Create: Insert data into the database
  • Read: Retrieve data from the database
  • Update: Modify existing data in the database
  • Delete: Remove data from the database

In a typical web application, these operations form the basis of interaction between the user and the backend database.

Setting Up the Environment

1. Installing MongoDB

Ensure that MongoDB is installed on your machine. You can download it from the official MongoDB website and follow the installation instructions for your operating system.

2. Setting Up a Node.js Project

mkdir mongo-crud-demo cd mongo-crud-demo npm init -y npm install mongoose

This creates a Node.js project and installs Mongoose.

3. Connecting to MongoDB

Create a file called db.js for the MongoDB connection:

// db.js const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/crud_demo', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('MongoDB connected'); }).catch(err => { console.error('Connection error:', err); });

This script connects your Node.js application to the MongoDB database named "crud_demo".

Defining a Mongoose Schema

Before performing CRUD operations, we need to define a schema and model:

// models/User.js const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); module.exports = mongoose.model('User', userSchema);

This defines a simple User model with fields: name, email, and age.

Performing CRUD Operations

Create Operation

To insert data into MongoDB, use the create or save method.

// create.js const mongoose = require('mongoose'); const User = require('./models/User'); require('./db'); const createUser = async () => { const user = new User({ name: 'Alice', email: 'alice@example.com', age: 25 }); await user.save(); console.log('User Created:', user); }; createUser();

This script adds a new user named Alice to the database.

Read Operation

To retrieve data from MongoDB, you can use methods like find, findOne, or findById.

// read.js const mongoose = require('mongoose'); const User = require('./models/User'); require('./db'); const readUsers = async () => { const users = await User.find(); // Fetch all users console.log('All Users:', users); const oneUser = await User.findOne({ name: 'Alice' }); console.log('Single User:', oneUser); }; readUsers();

Here, all users are fetched, and also a single user named Alice is retrieved.

Update Operation

You can update existing records using updateOne, updateMany, or findByIdAndUpdate.

// update.js const mongoose = require('mongoose'); const User = require('./models/User'); require('./db'); const updateUser = async () => { const updated = await User.findOneAndUpdate( { name: 'Alice' }, { age: 26 }, { new: true } ); console.log('Updated User:', updated); }; updateUser();

This updates Alice’s age to 26 and returns the modified document.

Delete Operation

To remove data from the database, use deleteOne, deleteMany, or findByIdAndDelete.

// delete.js const mongoose = require('mongoose'); const User = require('./models/User'); require('./db'); const deleteUser = async () => { const result = await User.deleteOne({ name: 'Alice' }); console.log('Deleted User:', result); }; deleteUser();

This deletes the user whose name is Alice from the database.

Advanced CRUD with Query Options

Filtering with Queries

const usersOver25 = await User.find({ age: { $gt: 25 } }); console.log('Users over 25:', usersOver25);

Filters users whose age is greater than 25.

Sorting and Limiting

const sortedUsers = await User.find().sort({ age: -1 }).limit(3); console.log('Top 3 oldest users:', sortedUsers);

Sorts by age in descending order and limits the result to 3 users.

Projections

const namesOnly = await User.find({}, 'name'); console.log('User Names:', namesOnly);

Retrieves only the names of all users.

Using async/await with Error Handling

const safeCreateUser = async () => { try { const user = new User({ name: 'Bob', email: 'bob@example.com', age: 30 }); await user.save(); console.log('User Saved:', user); } catch (error) { console.error('Error Saving User:', error.message); } };

Always wrap your asynchronous code in try/catch blocks to handle exceptions gracefully.

Bulk Operations

Inserting Multiple Documents

const insertManyUsers = async () => { const users = [ { name: 'John', email: 'john@example.com', age: 28 }, { name: 'Jane', email: 'jane@example.com', age: 22 }, { name: 'Jack', email: 'jack@example.com', age: 35 } ]; await User.insertMany(users); console.log('Users inserted'); };

Allows multiple documents to be inserted at once.

Deleting Multiple Documents

const deleteAllYoungerThan25 = async () => { const result = await User.deleteMany({ age: { $lt: 25 } }); console.log('Users Deleted:', result.deletedCount); };

This deletes all users under the age of 25.

Populating Related Data

Suppose you have a reference to another schema. You can use the populate method to join documents.

// models/Post.js const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: String, content: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }); module.exports = mongoose.model('Post', postSchema);
// fetchPosts.js const Post = require('./models/Post'); const fetchPostsWithUsers = async () => { const posts = await Post.find().populate('author'); console.log('Posts with Authors:', posts); };

CRUD operations in MongoDB, especially with the help of Mongoose, are powerful and flexible. Using Mongoose allows you to interact with MongoDB through a structured, schema-based approach, making your application more maintainable and less error-prone.

To summarize, you’ve learned how to:

  • Set up a Node.js project with MongoDB
  • Define a Mongoose schema and model
  • Perform Create, Read, Update, and Delete operations
  • Use advanced query features like sorting, filtering, and projections
  • Use populate to relate documents

Mastering CRUD in MongoDB is essential for any developer working with modern full-stack applications. With the knowledge and code examples provided in this guide, you should be well-equipped to perform and implement effective database operations in your projects.

Related Tutorials

Frequently Asked Questions for Node.js

A function passed as an argument and executed later.

Runs multiple instances to utilize multi-core systems.

Reusable blocks of code, exported and imported using require() or import.

nextTick() executes before setImmediate() in the event loop.

Starts a server and listens on specified port.

Node Package Manager β€” installs, manages, and shares JavaScript packages.

A minimal and flexible web application framework for Node.js.

A stream handles reading or writing data continuously.

It processes asynchronous callbacks and non-blocking I/O operations efficiently.

Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.

An object representing the eventual completion or failure of an asynchronous operation.

require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).

Use module.exports or exports.functionName.

Variables stored outside the code for configuration, accessed using process.env.


MongoDB, often used with Mongoose for schema management.

Describes project details and manages dependencies and scripts.

Synchronous blocks execution; asynchronous runs in background without blocking.

Allows or restricts resources shared between different origins.

Use try-catch, error events, or middleware for error handling.

Provides file system-related operations like read, write, delete.

Using event-driven architecture and non-blocking I/O.

Functions in Express that execute during request-response cycle.

A set of routes or endpoints to interact with server logic or databases.

Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.

Middleware to parse incoming request bodies, like JSON or form data.

line

Copyrights © 2024 letsupdateskills All rights reserved