Open In App

Mongoose Schema API

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Structure

Step 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.

1-66

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.

2-66

Performing Update Operations in Mongoose

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:

3-660

Step 3: Now, type in the URL http://localhost:5000/findUpdatedMobile and you will get the update document. You will see the following output.

4-660

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

  1. Data Integrity: Mongoose enforces schema rules and data validation, ensuring the correctness and consistency of data.
  2. Ease of Use: With methods like create(), save(), and find(), Mongoose abstracts much of the complexity of working with MongoDB.
  3. Built-in Middleware: Mongoose offers hooks for lifecycle events like pre-save, post-save, and validation, which can be used to implement business logic.
  4. 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.


Next Article

Similar Reads