Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB, providing a straightforward way to define the structure of documents, enforce validation, and handle database interactions. Mongoose SchemaTypes are key components that define the types of data stored in MongoDB collections, such as strings, numbers, dates.
What Are Mongoose SchemaTypes?
In Mongoose, SchemaTypes define the types of data that a specific field in a MongoDB collection can store. Each SchemaType corresponds to a specific MongoDB data type, allowing us to enforce consistent structure and validation rules for our documents.
Mongoose SchemaTypes support various data types, including strings, numbers, dates, arrays, objects, booleans, and more. By using SchemaTypes, Mongoose ensures that data is consistent and validates according to the type specified.
Syntax:
const schema = new Schema({
name: { type: String },
age: { type: Number, default: 10 },
});
Understanding the Purpose of Mongoose SchemaTypes
The purpose of using Mongoose SchemaTypes is to structure and validate data consistently. Here are some key reasons why SchemaTypes are important in MongoDB and Mongoose:
- Data Validation: SchemaTypes enforce validation rules that ensure data integrity before it is saved in the database.
- Type Safety: By defining specific types for each field, SchemaTypes help prevent type mismatches and errors.
- Query Optimization: Mongoose and MongoDB optimize queries based on the field types, improving performance when retrieving data.
- Default Values: SchemaTypes allow you to set default values for fields, ensuring that they are always initialized when a document is created.
How to Define Mongoose SchemaTypes
To define a SchemaType in Mongoose, we use the Schema() constructor. Here’s how to define a schema with various types:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: { type: String, required: true },
age: { type: Number, required: true },
birthdate: { type: Date, default: Date.now },
isActive: { type: Boolean, default: true },
skills: { type: [String] }, // Array of Strings
profileImage: { type: Buffer }, // Binary Data (Image)
friends: [{ type: Schema.Types.ObjectId, ref: 'User' }] // Array of ObjectIds for relationships
});
const User = mongoose.model('User', userSchema);
Explanation:
- String, Number, Boolean, Date, Buffer, and Array are used to define the field types.
- The
friends
field stores an array of ObjectIds, referencing documents in the User collection to create relationships.
Mongoose SchemaTypes and Validation
Mongoose SchemaTypes support various validation options to ensure that the data matches the expected format before saving it to the database. These validations include required, min, max, enum, match, and validate.
Example of Validation:
const productSchema = new Schema({
name: { type: String, required: true },
price: { type: Number, min: 0 },
category: { type: String, enum: ['Electronics', 'Clothing', 'Food'] }
});
const Product = mongoose.model('Product', productSchema);
Explanation:
- The
name
field is required. - The
price
field must be greater than or equal to 0. - The
category
field can only have values from a predefined set: "Electronics", "Clothing", or "Food".
Mongoose SchemaTypes for Special Data Types
1. ObjectId: References to Other Documents
The ObjectId type is used to reference other documents in different collections. This allows you to establish relationships between documents, much like foreign keys in relational databases.
const orderSchema = new Schema({
product: { type: Schema.Types.ObjectId, ref: 'Product' }, // Reference to the Product model
quantity: { type: Number, required: true }
});
const Order = mongoose.model('Order', orderSchema);
2. Decimal128: High Precision Floating-Point Numbers
For high-precision floating-point numbers (useful for financial data), Mongoose supports the Decimal128 type. This type ensures accuracy by using IEEE 754-2008 double-precision format.
const priceSchema = new Schema({
amount: { type: mongoose.Schema.Types.Decimal128, required: true }
});
const Price = mongoose.model('Price', priceSchema);
This ensures that financial data remains precise, even with very large or small numbers.
3. Mixed: Flexible Schema for Unstructured Data
The Mixed type allows us to store any kind of data in a field. This is useful for situations where the structure of the data may change or is dynamic.
const itemSchema = new Schema({
name: String,
data: Schema.Types.Mixed
});
const Item = mongoose.model('Item', itemSchema);
Steps to Create Project
Step 1: Create a folder and initialize it:
npm init
Step 2: Install mongoose in the project.
npm i mongoose
The project structure is as follows:
Step 3: Create a file called index.js. Inside the index.js, connect to MongoDB. Here the MongoDB Compass is used. First, create the Schema, then the Model from Schema, and name it Student. Finally, create a document of the Student model and save it to the database using the save() function.
// Filename - index.js
const mongoose = require("mongoose");
// Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {});
// Creating Schema
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, default: 8 },
skills: [{ type: String }],
dob: { type: Date },
});
// Student model
const Student = mongoose.model("Student", studentSchema);
// Creating Student document from Model
let student1 = new Student({
name: "GFG",
age: 12,
skills: ["Drawing", "Craft", "Football"],
dob: new Date("2010-08-08"),
});
// Saving to database
student1.save().then(async (doc) => {
if (doc) {
console.log("The student data saved succesfully");
}
});
Step 4: Now run the code using the following command in the Terminal/Command Prompt to run the file.
node index.js
Output:
And the document in the MongoDB is as follows:
Best Practices When Using Mongoose SchemaTypes
1. Always Use Validation: Define clear validation rules for our schema fields to prevent invalid data from being saved to the database.
2. Leverage Default Values: Use the default
option to provide default values for fields that are not explicitly set.
3. Limit Use of Mixed Type: While the Mixed type offers flexibility, it bypasses validation, so use it sparingly and only for truly dynamic data.
4. Optimize for Performance: Use appropriate types, like ObjectId for references, to maintain efficient querying and indexing.
Conclusion
Mongoose SchemaTypes are a critical part of MongoDB data modeling, enabling developers to define and enforce the structure of documents. By using the correct SchemaTypes, you can ensure your data is consistent, validated, and optimized for querying. With built-in support for a wide range of data types, including strings, numbers, booleans, and references, Mongoose simplifies data modeling and validation in your Node.js 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