Mongoose.model() Function
Last Updated :
21 Mar, 2025
The mongoose.model()
function is a core method in the Mongoose library, used for interacting with MongoDB in a Node.js environment. It helps in creating a MongoDB collection associated with a schema, defining the structure of documents that will be stored within it. This article will explain mongoose.model()
function, its syntax, parameters, and provide practical examples to help us understand how to use it effectively in our applications.
What is the mongoose.model()
Function?
The mongoose.model()
function is used to create models in Mongoose, which act as the interface to MongoDB collections. A model is a constructor function that allows us to create, query, update, and delete documents within a specific MongoDB collection.
When creating a model, Mongoose automatically uses the singular, capitalized form of the model name, pluralizes it, and associates it with a MongoDB collection. For instance, creating a model called User
will result in the collection being named users
in MongoDB.
Why Use Mongoose Models?
- Data Integrity: Models are based on schemas, ensuring that data stored in the database adheres to a defined structure.
- Ease of Use: Mongoose provides built-in methods for handling CRUD (Create, Read, Update, Delete) operations and validating data before saving it.
- Powerful Querying: Models allow you to execute advanced queries with Mongoose's rich query API.
Syntax:
mongoose.model(<ModelName>, <Schema>)
Parameters:
- Model Name: This is the name of the model. The name is used by Mongoose to create the corresponding MongoDB collection. Mongoose automatically pluralizes and converts the name to lowercase (e.g.,
User
will correspond to the users
collection).
- Schema: The schema defines the structure of the documents that the model will represent. It is created using the
mongoose.Schema()
function, where you specify the fields and their types.
Return type:
- The
mongoose.model()
function returns a model object, which is used to interact with the MongoDB collection.
How to Create a Model with mongoose.model()
?
Creating a model involves two steps:
- Define the Schema: First, we need to create a schema that outlines the structure of the documents in your collection.
- Create the Model: Then, use the
mongoose.model()
function to create a model from the schema.
Example: Creating a Model in Mongoose
// Importing mongoose module
const mongoose = require("mongoose")
// Database Address
const url = "mongodb://localhost:27017/GFG"
// Connecting to database
mongoose.connect(url).then((ans) => {
console.log("ConnectedSuccessful")
}).catch((err) => {
console.log("Error in the Connection")
})
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
const collection_structure = new Schema({
name: {
type: String,
require: true
}
,
marks: {
type: Number,
default: 0
}
})
// Creating collection
const collections = mongoose.model("GFG", collection_structure)
// Inserting one document
collections.create({
name: "aayush",
marks: 10
}).then((ans) => {
console.log("Document inserted")
}).catch((err) => {
console.log(err.Message);
})
Steps to Run the Application:
1. Installing Module: Install the mongoose module using the following command:
npm install mongoose
Project Structure: Our project structure will look like this:

2. Running the server on Local IP: Data is the directory where MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1

3. Run index.js file using below command:
node index.js
Output:

MongoDB Database: Our database after executing the above command will look like this:

Running the Server and Output
When you run the application, the following happens:
- Connection to MongoDB: The
mongoose.connect()
method connects your Node.js application to the MongoDB database. If successful, you'll see the message "Connected to MongoDB successfully."
- Schema and Model Creation: The schema defines the structure of the documents (fields like
name
and marks
), and the model is created using mongoose.model()
. - Document Insertion: A new document with the values
{name: "Aayush", marks: 10}
is inserted into the gfgs
collection. If successful, the message "Document inserted successfully."
will appear.
MongoDB Database Output
After executing the code, the MongoDB database (GFG
) will contain a collection named gfgs
with a document similar to the following:
{
"_id": ObjectId("1234567890abcdef12345678"),
"name": "Aayush",
"marks": 10
}
Conclusion
The mongoose.model()
function is crucial for interacting with MongoDB in Node.js applications. It creates a model based on a schema, allowing us to manage documents efficiently while ensuring data integrity. With its simple syntax and powerful features, mongoose.model()
is an essential tool in any MongoDB-powered Node.js project. By following the examples and tips provided in this article, we can efficiently use the mongoose.model()
function to create models and manage your MongoDB collections in Node.js.
Similar Reads
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
ACID Properties in DBMS
In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read