Mongoose is a JavaScript library that allows us to work with MongoDB in a structured yet fast way, using a schema-based approach.
It provides an elegant solution for modeling our application’s data and performing CRUD (Create, Read, Update, Delete) operations with ease.
Mongoose stands out for the following features:
- Schema Modeling: Defines the structure of our MongoDB documents through schemas.
- Validation: Validates data before saving it to the database.
- Advanced Queries: Performs complex queries easily.
- Middleware: Uses middleware to perform operations before or after specific events.
- Plugins: Extends functionality through a wide range of plugins.
For more information about Mongoose, you can visit the official Mongoose website, check the Mongoose documentation, or explore the repository on GitHub.
Installing Mongoose
To start using Mongoose in our applications, we first need to install it. If we are using npm, we can do so with the following command:
npm install mongoose
How to Use Mongoose
Connecting to MongoDB
First, we need to connect to a MongoDB instance.
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/test');
Defining Schemas and Models
With Mongoose, we define the structure of our documents through schemas. For example, let’s see how we can define a model to save Users.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, min: 0 }
});
const User = mongoose.model('user', userSchema);
That is the normal syntax. But we also have a more concise one, without having to create the Schema.
const Cat = mongoose.model('Cat', { name: String });
Creating Documents
To create a new document, we use the model we defined earlier.
const newUser = new User({ name: 'Luis' } );
newUser.save().then(() => console.log('Luis'));
Reading Documents
We can read documents from the database using methods like find, findOne, findById, etc.
User.find({ name: 'Luis'})
.then((items) => console.log(`${items}`));
Updating Documents
To update a document, we use methods like updateOne, updateMany, findByIdAndUpdate, etc.
User.updateOne({ name: 'Luis'}, { age: '35'})
.then((ev) => console.log(ev));
Deleting Documents
We can delete documents from the database using methods like deleteOne, deleteMany, findByIdAndDelete, etc.
User.deleteOne({ name: 'Luis'})
.then(() => console.log('User deleted'))
.catch((err) => console.log(err));

