Mongoose is a powerful ODM (Object Document Mapper) tool for Node.js, specifically designed to work with MongoDB. It offers an easy way to define data models, interact with the database, and enforce data integrity in MongoDB through schemas. In this article, we will explore the Mongoose Schema API, covering how to define schemas, create models, and perform CRUD operations.
Whether you're a beginner or experienced developer, this article will help us understand the essentials of Mongoose and how to use its schema features to streamline database interactions.
What is Mongoose and the Schema API?
Mongoose is a package offered for Node JS in order to handle the querying, building schemas, and working out the business logic using MongoDB. Mongoose provides the ability to connect to a MongoDB instance, either local or a cloud-based instance.
Mongoose provides a long list of APIs in order to work and communicate with the database. One of them is the Schema API. Whenever we want to store any kind of data inside our database, we need to follow a particular schema according to which our data will be stored. For example, a schema to store an exercise will contain the following fields - exercise-name, exercise-description, and exercise-duration.
Syntax:
The syntax for creating a new schema using the Schema API is as follows
const newEntity = new mongoose.Schema({
field1: type of field(String/Number/Boolean and more)
field2: type of field
...
})
Key Mongoose Schema Functions
The most important functions which are used while working with the Schema API are as follows:
1. Schema(): This function helps us to define the schema of the entity we want to store inside our database. The function takes as an input, all the fields of the entity, such as username, age, email, etc.
2. model(): This function helps us to create a model/instance of a record of the entity we want to insert in our database. Once a model is created, we can use all the database operations such as insert, update, find, delete, etc. The function takes as an input, the name of our model and the schema of the entity we wish to store inside our database.
Example of Working with Mongoose Schema API
Let us take a look at some examples to understand the Mongoose Schema API.
Step 1: Set Up Your Project
Create a new folder called mongoose_examples. Open your command prompt and navigate to this folder. Now, type in the following command:
mkdir mongoose_examples
cd mongoose_examples
npm init -y
This will setup the package.json file for us, so that we can install all the necessary packages. Now, open your command prompt and type in the following command-
npm install mongoose express
This will install the mongoose and express packages for us. Now, inside the mongoose_examples folder, create a new file called index.js. Your final folder structure should look like this.
Final Folder StructureStep 2: Create the index.js
File
Open index.js. In the first example, we are creating an exercise schema, inserting some data inside it, and finally, reading the data, and displaying it on the webpage.
Filename: index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 5000;
const uri = 'mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.4';
mongoose.connect(uri);
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Connected to MongoDB successfully.');
});
const Schema = mongoose.Schema;
const newExercise = new Schema({
name: { type: String },
description: { type: String },
duration: { type: Number }
});
const Exercise = mongoose.model('Exercise', newExercise);
app.post('/insertExercise', (req, res) => {
Exercise.create({
name: 'Cycling',
description: 'Cycling on the road',
duration: 30
});
res.send('Exercise inserted successfully.');
});
app.get('/findExercises', (req, res) => {
Exercise.find()
.then((exercise) => res.send(exercise))
.catch((error) => res.send('Error' + error));
});
app.get('/', (req, res) => {
res.send('Mongoose Schema API');
});
app.listen(port, () => {
console.log(`Server is listening on the port ${port}.`);
});
Step 3: Run the Application
Once your index.js file is ready, run the application using the following command:
node index.js
You should see something like this in your terminal:
Server is listening on the port 5000.
Connected to MongoDB successfully.
Step 4: Insert Data
Go to the URL http://localhost:5000/insertExercise and perform a post request to insert an exercise. We will be using Thunderclient for the same which is a VS Code Extension for performing GET, POST, DELETE requests. You will get the following output.
Step 5: Retrieve Data
Once the data is inserted, you can view it by visiting http://localhost:5000/exercises
. This will return the list of all exercises stored in the MongoDB database.
In the next example, we will perform an update operation using Mongoose. Here’s an example where we update the price of a mobile item in a database. For the same, we have already created the following sample database.
Step 1: Open index.js. What we are doing here is updating the price of Samsung 30s from 22000 to 30000. We will use the updateOne function provided by Mongoose for the same.
Filename: index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 5000;
const uri =
'mongodb://127.0.0.1:27017/pranav?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.4';
mongoose.connect(uri);
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Connected to MongoDB successfully.');
});
const Schema = mongoose.Schema;
const newMobile = Schema({
name: { type: String },
price: { type: Number },
rating: { type: Number },
isBig: { type: Boolean }
});
const Item = mongoose.model('Item', newMobile);
app.post('/updateMobile', (req, res) => {
Item.updateOne(
{ name: 'Samsung 30s' },
{ price: 30000 },
(err, docs) => {
if (err) {
res.send(err);
}
else {
res.send('Document updated successfully.');
}
})
});
app.get('/findUpdatedMobile', (req, res) => {
Item.findOne({ name: 'Samsung 30s' })
.then((mobile) => res.send(mobile))
.catch((err) => res.send(err));
});
app.get('/', (req, res) => {
res.send('Mongoose Schema API');
});
app.listen(port, () => {
console.log(`Server is listening on the port ${port}.`);
});
Step 2: Now go to your ThunderClient. Type in the URL http://localhost:5000/updateMobile and perform a post request. You will see the following output:
Step 3: Now, type in the URL http://localhost:5000/findUpdatedMobile and you will get the update document. You will see the following output.
Explanation: This example updates the price of a specific mobile phone model. It shows how to find a document and replace or modify specific fields using Mongoose.
Why Use Mongoose? Key Benefits
- Data Integrity: Mongoose enforces schema rules and data validation, ensuring the correctness and consistency of data.
- Ease of Use: With methods like
create()
, save()
, and find()
, Mongoose abstracts much of the complexity of working with MongoDB. - Built-in Middleware: Mongoose offers hooks for lifecycle events like pre-save, post-save, and validation, which can be used to implement business logic.
- Population: Mongoose supports populate(), a function that automatically replaces the references of documents in one collection with documents from another collection
Conclusion
In this article, we have covered how to define a Mongoose Schema, create models, and perform common CRUD operations. Whether you're building a simple CRUD application or a complex system, Mongoose's Schema API provides a powerful way to interact with MongoDB in a structured and consistent manner. Now that you understand the basics of Mongoose, try implementing a schema for your own application. Explore additional features like middleware and population to further enhance your data management.
Similar Reads
Mongoose Tutorial
Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
Mongoose Schemas
Mongoose Schemas Creating a Model
Mongoose is one of the most popular Object Data Modeling (ODM) libraries for MongoDB, providing schema-based solutions to model our application's data. This allows us to define the structure of documents within a MongoDB collection, including validation, typecasting, and other powerful features that
5 min read
Mongoose Schemas and Indexes
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB in a Node.js environment. It provides a straightforward way to interact with MongoDB, including features like schema definition, model creation, and database query handling. One key feature of Mongoose is its ability to create and
5 min read
Mongoose Schemas Instance methods
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB, designed to work in a Node.js environment. One of the key features of Mongoose is its ability to define instance methods on schema objects, which allow you to perform operations on individual documents. This guide will explore Mo
5 min read
Mongoose Schemas Ids
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a
2 min read
Mongoose Schemas Virtuals
Virtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive
6 min read
Mongoose Schemas Aliases
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability. Creating node application And Installing Mongoose: Step 1: Create a
2 min read
Mongoose Schemas With ES6 Classes
Mongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec
2 min read
Mongoose Schemas Query Helpers
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl
3 min read
Mongoose Documents
Mongoose Documents
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js, making it easier to interact with MongoDB databases. It provides a structured way to handle data, perform validation, and manage documents in MongoDB with ease. In this article, we will explain Mongoose Documents, how
5 min read
Mongoose Documents vs Models
Mongoose, a popular Node library, is widely used for interacting with MongoDB, a NoSQL database. Mongoose simplifies the process of working with MongoDB by providing an object data modeling (ODM) framework. In the Mongoose ecosystem, two key concepts are Documents and Models. In this article, we'll
4 min read
Mongoose Documents Updating Using save()
An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document.We will take the help of an example to underst
5 min read
Mongoose Queries
Mongoose Queries
Mongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read
Mongoose deleteMany() Function
The deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it
4 min read
Mongoose Queries Model.replaceOne() Function
The Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameter
3 min read
Find() Method in Mongoose
The Mongoose find() method is one of the most widely used methods for querying MongoDB collections in Node.js. It provides a flexible and powerful way to fetch data from your MongoDB database. In this article, we will explore the find() method in detail, its syntax, parameters, and how to implement
5 min read
FindById Method in Mongoose
The findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl
4 min read
Mongoose QueriesModel.findByIdAndDelete() Method
The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
Mongoose findByIdAndRemove() Function
MongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i
2 min read
Mongoose QueriesModel.findByIdAndDelete() Method
The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
FindOne() Method in Mongoose
The findOne() method in Mongoose is one of the most commonly used functions for querying data from a MongoDB database. It provides a simple and efficient way to retrieve a single document that matches a specified query condition. This article will explore how to use the findOne() method, explain its
5 min read
Mongoose findOneAndDelete() Function
The findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In
5 min read
Mongoose | findOneAndRemove() Function
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin
2 min read
Mongoose | findOneAndReplace() Function
When working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace(). This function helps in finding a document and replacing it with a new one. But how exactly
5 min read
Mongoose Queries Model.findOneAndUpdate() Function
The Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt
3 min read
Mongoose Document Model.replaceOne() API
The Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters: Â The Mo
3 min read
updateMany() Method in Mongoose
In Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document,
4 min read
Mongoose Queries Model.updateOne() Function
The Queries Model.updateOne() function of the Mongoose API is used to update an existing document with the information mentioned in the "update" object. It updates only the first document that is returned in the filter. Syntax: Model.updateOne(filter, update, options, callback ) Parameters: It accep
3 min read