How to Perform CRUD Operations with Mongoose
How to Perform CRUD Operations with Mongoose
Mongoose is a popular ODM (Object Data Modeling) library that makes it easy to perform operations on a MongoDB database in Node.js applications. It especially provides convenience and type safety for CRUD operations (Create, Read, Update, Delete). In this article, we will cover the topic of "CRUD Operations with Mongoose" step-by-step with detailed code examples.
Mongoose Installation and Model Creation
First, add the required Mongoose package to your project and establish the MongoDB connection. Then let's define a sample user (User) model:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/blog', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
CRUD Operations with Mongoose
1. Create (Add)
To add a new user, we can use the .create() method or the .save() method with an instance of the model.
// Add a new user
User.create({ name: 'Ayşe', email: 'ayse@mail.com', age: 24 })
.then(user => console.log(user))
.catch(err => console.error(err));
2. Read (Retrieve)
To list users or search for one, the .find() and .findOne() functions are commonly used.
// Retrieve all users
User.find()
.then(users => console.log(users))
.catch(err => console.error(err));
// Find a specific user
User.findOne({ email: 'ayse@mail.com' })
.then(user => console.log(user))
.catch(err => console.error(err));
3. Update
The .findByIdAndUpdate() function is very useful for updating a user.
// Update a user by specific ID
User.findByIdAndUpdate('USER_ID', { age: 25 }, { new: true })
.then(user => console.log(user))
.catch(err => console.error(err));
4. Delete
To delete a user, you can use .findByIdAndDelete() or .deleteOne().
// Delete a user by specific ID
User.findByIdAndDelete('USER_ID')
.then(result => console.log('Deleted: ', result))
.catch(err => console.error(err));
Conclusion
With Mongoose, CRUD operations allow you to manage data securely and easily on MongoDB. With these basic methods mentioned under the title CRUD operations with Mongoose, you can quickly use data addition, read, update, and delete functions in your projects. Thus, your Node.js and MongoDB-based applications become easier to maintain and more sustainable.

Yorum Gönder