Open In App

Mongoose Schemas Creating a Model

Last Updated : 18 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 simplify database operations.

What is Mongoose Schema and Model?

Before diving into creating a model, it's important to understand the schema and model concepts in MongoDB:

Schema: A MongoDB schema defines the structure of documents within a collection. It specifies the fields, their types, validation rules, default values, and other constraints.

Model: A model is a wrapper around the schema that allows us to interact with the MongoDB database (CRUD operations like create, read, update, delete). It provides an interface for querying and manipulating the data.

Steps to Create Model with Mongoose Schema

To demonstrate how to create a model using Mongoose, follow these steps to set up the environment:

Step 1: Initialize a Node.js Project

First, we need to create a Node.js project if you haven't done so already. Run the following command in your terminal:

npm init -y

This will generate a package.json file, which will manage the project's dependencies.

"start": "node app.js" 
package.json

We can start the developement server using the below command.

npm start

Note: The above command will not do anything right now since we have not written any code in our JavaScript file.

Step 2: Install Mongoose and MongoDB Dependencies

We need to install the required modules to use in our project. Run the following command to install mongoose and mongosd as dependencies.

npm install mongodb mongoose

Step 3: Create the app.js File

Now, create an app.js file where you will define the Mongoose schema and model and connect to MongoDB. Start by connecting to your MongoDB instance:

// app.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/magesDB', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.log('Could not connect to MongoDB...', err));

Step 4: Define the Mongoose Schema

To create a schema and model in Mongoose, define a schema with fields like name, power type, gold, health, and mana for a "Mage." Use mongoose.Schema() to set up the structure, ensuring required fields. Then, use mongoose.model() to create a model based on this schema, enabling interaction with the database.

// Filename - app.js

const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
power_type: {
type: String,
require: true
},
mana_power: Number,
health: Number,
gold: Number
})

Step 5: Create the Model Using the Schema

Once the schema is defined, create a model using mongoose.model(). This model will provide an interface to interact with the mages collection in the MongoDB database.

const Mage = mongoose.model('Mage', mageSchema);

Step 6: Create and Save Documents Using the Model

To create and save a model in Mongoose, instantiate an object from the model class using the new keyword, then call the save() method on this object to create a document in the corresponding MongoDB collection.

// Filename - app.js

const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
power_type: {
type: String,
require: true
},
mana_power: Number,
health: Number,
gold: Number
})

const Mage = new mongoose.model("Mage", mageSchema)

const mage_1 = new Mage({
name: "Takashi",
power_type: 'Element',
mana_power: 200,
health: 1000,
gold: 10000
});

mage_1.save();

We can view the saved model and document by opening up the Studio 3T desktop application, clicking on connect, and then going through the following hierarchy and double click on the mode collection name.

This is what you will see when you double-click on the collection name. Notice that it has been given an _id field automatically.

We can create as many objects from the Mage class as you want, and call the save() method on them to create a document for each of them in the mages collection.

// Filename - app.js

const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
power_type: {
type: String,
require: true
},
mana_power: Number,
health: Number,
gold: Number
})

const Mage = new mongoose.model("Mage", mageSchema)

const mage_1 = new Mage({
name: "Takashi",
power_type: 'Element',
mana_power: 200,
health: 1000,
gold: 10000
});

mage_1.save();

const mage_2 = new Mage({
name: "Steve",
power_type: 'Physical',
mana_power: "500",
health: "5000",
gold: "50"
})

mage_2.save();

Re-start the server:

npm start

Output:

Benefits of Using Mongoose Schema and Model

1. Schema Validation: Mongoose automatically validates data based on the defined schema before saving it to the database.

2. Ease of Use: Mongoose provides a simple interface to work with MongoDB, eliminating the need to write complex queries manually.

3. Middleware Support: Mongoose supports middleware (pre and post hooks), allowing you to run custom logic before or after database operations.

4. Query Building: Mongoose simplifies querying with its chainable query-building API.

Conclusion

Mongoose is a powerful tool for managing MongoDB collections in a Node.js application. By defining schemas and models, Mongoose allows us to structure your data, perform validation, and interact with MongoDB in a straightforward and efficient manner. With the ability to create complex models, define indexes, and validate documents, Mongoose significantly streamlines the development of MongoDB-based applications.


Next Article

Similar Reads