Mongoose Schemas Creating a Model
Last Updated :
18 Mar, 2025
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.jsonWe 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.
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 ModelMongoose 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 IndexesMongoose 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 methodsMongoose 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 IdsMongoose 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 VirtualsVirtuals 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 AliasesMongoose 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 ClassesMongoose 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 HelpersMongoose 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 SchemaTypes
Mongoose Documents
Mongoose Queries
Mongoose QueriesMongoose 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() FunctionThe 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() FunctionThe 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 MongooseThe 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 MongooseThe 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() MethodThe 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() FunctionMongoDB 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() MethodThe 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 MongooseThe 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() FunctionThe 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() FunctionThe 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() FunctionWhen 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() FunctionThe 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() APIThe 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 MongooseIn 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() FunctionThe Model.updateOne() function in Mongoose is a powerful method used to update a single document within a MongoDB collection. It allows you to specify the conditions for selecting a document and then provides a way to apply updates to that document. In this article, we will explore how updateOne() w
4 min read
Mongoose Populate
Mongoose Schema API
Mongoose Connection API
Mongoose Document API
Mongoose Model API