Open In App

How to Register and Call a Schema in Mongoose?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and schema-based solution to model our application data. Understanding how to properly define and work with Mongoose schemas is essential for efficient MongoDB management and data interaction in Node.js applications.

Understanding Mongoose Schemas

Before diving into how to register and call a schema, it's important to first understand what a Mongoose schema is. A schema is essentially a blueprint that defines the structure of documents within a MongoDB collection. It specifies the fields, their data types, validation rules, default values, and other options.

In Mongoose, schemas enable data validation, default settings, and custom middleware for operations like saving or updating documents. They allow us to enforce data integrity and provide a solid structure to your documents.

How to Define a Schema in Mongoose

A Mongoose schema is defined using the mongoose.Schema() constructor. Here’s a simple example of defining a schema for a User document:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
username: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18 }
});

Explanation:

  • username is required and a String.
  • email is unique and required.
  • age is a Number with a minimum value of 18.
  • createdAt has a default value of the current date and time.

How to Register a Schema in Mongoose

After that, we will need to create a model in Mongoose for registering the schema we have used. Models are constructors created from schema which in turn describe documents within MongoDB collections. It is possible to develop a model by making use of Mongoose.model() function, which is called with the name of the model and the schema definition as parameters.

const User = mongoose.model('User', userSchema);

Explanation:

  • 'User' is the name of the model, which represents the User collection in MongoDB.
  • userSchema is the schema you’ve defined earlier.

How to Call a Schema in Mongoose

Once you’ve registered your schema as a model, we can use it to interact with your MongoDB collection. Mongoose models provide a range of methods to perform CRUD operations, such as creating, reading, updating, and deleting documents.

1. Creating a new document

To create a new document in the MongoDB collection, instantiate the model and call the save() method:

const newUser = new User({
username: 'john_doe',
email: '[email protected]',
age: 25
});

newUser.save()
.then(user => {
console.log('User created:', user);
})
.catch(error => {
console.error('Error creating user:', error);
});

Output:

User created: {
_id: ObjectId("60ad7b7b2c89d700155eecc3"),
username: 'john_doe',
email: '[email protected]',
age: 25
}

Explanation: In the above code snippet we create a new `User` object with the specified `username`, `email`, and `age`, and then save it to the database using Mongoose's `save()` method. If the operation is successful, it logs the newly created user object to the console. If an error occurs during the saving process, it logs the error to the console.

2. Querying documents

We can retrieve documents from MongoDB by using methods like .find(), .findOne(), and .findById(). Here’s an example of Retrieving users with the age of 25 from the database.

User.find({ age: 25 })
.then(users => {
console.log('Users with age 25:', users);
})
.catch(error => {
console.error('Error finding users:', error);
});

Output:

Users with age 25: [
{
_id: ObjectId("60ad7b7b2c89d700155eecc3"),
username: 'john_doe',
email: '[email protected]',
age: 25
}
]

Explanation: The above code snippet finds all users with an age of 25 in the database using Mongoose's find() method. If the operation is successful, it logs the users with the age of 25 to the console. If an error occurs during the finding process, it logs the error to the console.

3. Updating documents

To update a document, we can use the .findOneAndUpdate() method. We will Update the age of the user with the username 'john_doe' to 30.

User.findOneAndUpdate({ username: 'john_doe' }, { age: 30 }, { new: true })
.then(updatedUser => {
console.log('Updated user:', updatedUser);
})
.catch(error => {
console.error('Error updating user:', error);
});

Output:

Updated user: {
_id: ObjectId("60ad7b7b2c89d700155eecc3"),
username: 'john_doe',
email: '[email protected]',
age: 30
}

Explanation: In the above code snippet finds a user with the username 'john_doe' in the database and updates their age to 30 using Mongoose's findOneAndUpdate() method with the new: true option, which returns the updated document. If the operation is successful, it logs the updated user to the console.

4. Deleting documents

To delete a document, use the .findOneAndDelete() method. We will Delete the user with the username 'john_doe' from the database.

User.findOneAndDelete({ username: 'john_doe' })
.then(deletedUser => {
console.log('Deleted user:', deletedUser);
})
.catch(error => {
console.error('Error deleting user:', error);
});

Output:

Deleted user: {
_id: ObjectId("60ad7b7b2c89d700155eecc3"),
username: 'john_doe',
email: '[email protected]',
age: 30
}

Explanation: The above code snippet finds a user with the username 'john_doe' in the database and deletes that user using Mongoose's findOneAndDelete() method. If the operation is successful, it logs the deleted user to the console.

Conclusion

In Mongoose, schemas provide a powerful way to define the structure and rules for your documents in MongoDB collections. Models are created from schemas and serve as an interface for interacting with the database. By understanding how to define, register, and call schemas, you can easily perform CRUD operations and manage your MongoDB data efficiently in Node.js applications. With Mongoose’s schema-based approach, you can ensure data integrity, simplify database interactions, and create scalable, maintainable applications.


Article Tags :

Similar Reads