CRUD Operations with Mongoose
Course Title: Mastering Express.js: Building Scalable Web Applications and APIs Section Title: Working with Databases: MongoDB and Mongoose Topic: CRUD operations with Mongoose (Create, Read, Update, Delete)
In this topic, we'll explore the fundamental operations of any database: Create, Read, Update, and Delete (CRUD). Understanding how to perform these operations is crucial for building robust and scalable web applications. We'll learn how to use Mongoose to interact with our MongoDB database and perform CRUD operations efficiently.
Creating Documents with Mongoose
Creating documents in Mongoose involves defining a model and then using the create()
method or the save()
method.
Example:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const User = mongoose.model('User', userSchema);
const user = new User({ name: 'John Doe', email: 'john.doe@example.com' });
user.save((err, user) => {
if (err) {
console.log(err);
} else {
console.log(`User created: ${user.name}`);
}
});
In this example, we define a User
model and create a new user document using the new
keyword. We then use the save()
method to save the document to the database.
Alternatively, we can use the create()
method to create multiple documents at once:
User.create([{ name: 'Jane Doe', email: 'jane.doe@example.com' }, { name: 'Bob Smith', email: 'bob.smith@example.com' }])
.then(users => {
console.log(`Users created: ${users.map(user => user.name)}`);
})
.catch(err => {
console.log(err);
});
Reading Documents with Mongoose
Reading documents in Mongoose involves using various query methods to find and retrieve documents from the database.
Example:
User.findOne({ email: 'john.doe@example.com' }, (err, user) => {
if (err) {
console.log(err);
} else {
console.log(`User found: ${user.name}`);
}
});
In this example, we use the findOne()
method to find a user document with a specific email address. We can also use other query methods like find()
, findById()
, and findByIdAndUpdate()
.
Updating Documents with Mongoose
Updating documents in Mongoose involves using various query methods to update existing documents in the database.
Example:
User.findByIdAndUpdate('1234567890', { name: 'John Doe Updated' }, (err, user) => {
if (err) {
console.log(err);
} else {
console.log(`User updated: ${user.name}`);
}
});
In this example, we use the findByIdAndUpdate()
method to update a user document with a specific ID. We can also use other query methods like updateOne()
, updateMany()
, and findOneAndUpdate()
.
Deleting Documents with Mongoose
Deleting documents in Mongoose involves using various query methods to remove existing documents from the database.
Example:
User.findByIdAndRemove('1234567890', (err, user) => {
if (err) {
console.log(err);
} else {
console.log(`User deleted: ${user.name}`);
}
});
In this example, we use the findByIdAndRemove()
method to delete a user document with a specific ID. We can also use other query methods like deleteOne()
and deleteMany()
.
Conclusion
In this topic, we covered the fundamental CRUD operations with Mongoose, including creating, reading, updating, and deleting documents. We learned how to use various query methods to interact with our MongoDB database efficiently.
Practice Exercise:
Create a Node.js application that performs the following CRUD operations using Mongoose:
- Create a new user document with the email address "example@example.com".
- Read all user documents and log them to the console.
- Update the user document with the email address "example@example.com" to have a new name "Updated User".
- Delete the user document with the email address "example@example.com".
Additional Resources:
**Leave a comment or ask for help below if you have any questions or need further clarification on this topic. We'll review the responses and provide guidance as needed.
In the next topic, we'll cover "Defining schemas and validating data."
Images

Comments