Open In App

How to Define Schema and Model in Mongoose?

Last Updated : 20 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Mongoose is a widely used Object Data Modeling (ODM) library designed for MongoDB in Node.js applications It provides a straightforward way for interacting with MongoDB by offering a schema-based structure. In this article article, we will go through the process of defining schemas and models in Mongoose by covering essential concepts and practical examples.

What is Mongoose Schema?

In Mongoose, Schema defines the structure of MongoDB documents within a collection. It specifies the fields, their types, default values, validations, and other properties. On the other hand, a Model in Mongoose is a compiled constructor for a document that provides an interface for interacting with the database collection. It represents a collection of documents and includes methods for querying, saving, updating, and deleting data.

Why Use Mongoose Schema?

  • Enforces structure in MongoDB documents.
  • Provides built-in validation and custom validation.
  • Allows you to define default values and indexes for fields.
  • Ensures data integrity and consistency.

What is a Mongoose Model?

A Model is a compiled version of a schema. It provides an interface to interact with the database collection, offering methods for creating, querying, updating, and deleting documents. Models are essential for performing CRUD operations on MongoDB data.

Key Differences Between Schema and Model

  • Schema: Defines the structure and data types for the collection.
  • Model: A constructor based on the schema that gives access to methods for querying, updating, and manipulating documents in the collection.

Step-by-Step Guide to Define Schema and Create Model in Mongoose

1. Install Mongoose

Before start using Mongoose, we need to install it in our Node.js project. Use npm or yarn to install the Mongoose library:

npm install mongoose

2. Connect to MongoDB

Once Mongoose is installed, the next step is to establish a connection to our MongoDB database.

// Importing Mongoose
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true, // Using the new URL parser
useUnifiedTopology: true // Using the new Server Discover and Monitoring engine
})
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.error('Error connecting to MongoDB:', error));

Output

Connected to MongoDB

Explanation: In this above code, replace 'mongodb://localhost:27017/myDatabase' with the actual MongoDB connection string. The useNewUrlParser and useUnifiedTopology options are recommended for better compatibility with newer MongoDB drivers.

3. Defining a Schema in Mongoose

A Schema in Mongoose is like a blueprint for the data. It outlines the fields that the documents will have, their data types, validation rules, and other configurations. Below is the basic syntax for creating a Schema:

// Importing mongoose
const mongoose = require('mongoose');

// Defining a schema for a user
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 18
},
createdAt: {
type: Date,
default: Date.now
}
});

Explanation: In this above example, we define a userSchema with fields name, email, age, and createdAt. We specify their data types (String, Number, Date), and add validation rules like required, unique, lowercase, and min.

4. Creating a Model from a Schema

Once we have a Schema, we can create a Model from it. A Model represents a collection in the MongoDB database and provides methods to interact with the data. Below is code to create a Model:

// Creating a model from the schema
const User = mongoose.model('User', userSchema);

Now, User is a Model that we can use to perform CRUD operations (Create, Read, Update, Delete) on our users collection.

5. Using the Model

Now, let's create, read, update, and delete user using the model.

Example 1: Creating a User

To create a new user document, instantiate the model and use the save() method to insert it into the database:

const newUser = new User({
name: 'Alice', // Setting the name field
email: '[email protected]', // Setting the email field
age: 25 // Setting the age field
});

newUser.save() // Saving the new user document to the database
.then(user => console.log('User created:', user)) // On success, log the created user
.catch(error => console.error(error)); // On error, log the error

Output

User created: {
_id: 60d9c6f8b60c0c1e2c39e9e3,
name: 'Alice',
email: '[email protected]',
age: 25,
createdAt: '2024-06-28T12:34:56.789Z'
}

The above code creates a new User document with the specified data and saves it to the database like above output.

Example 2: Finding Users

To find users based on a query, you can use methods like find():

User.find({ age: { $gte: 30 } }) // Finding users with age greater than or equal to 30
.then(users => console.log('Users aged 30 or older:', users)) // On success, log the found users
.catch(error => console.error(error)); // On error, log the error

Output

Users aged 30 or older: [
{
_id: 60d9c6f8b60c0c1e2c39e9e3,
name: 'John Doe',
email: '[email protected]',
age: 35,
createdAt: '2024-06-28T12:34:56.789Z'
}
]

This above code finds all users in the database who are '30 years old or older' which is John Doe only.

Example 3: Updating a User

Use the updateOne() method to update a user's details:

User.updateOne({ email: '[email protected]' }, { name: 'Alice Smith' }) // Updating the name field of the user with the specified email
.then(result => console.log('User updated:', result)) // On success, log the result of the update
.catch(error => console.error(error)); // On error, log the error

Output

User updated: { n: 1, nModified: 1, ok: 1 }

Above code updates the name of the user 'Alice Smith' with the email [email protected].

Example 4: Deleting a User

To delete a user, we can use the deleteOne() method:

// Deleting one user from email id
User.deleteOne({ email: '[email protected]' })
.then(result => console.log('User deleted:', result))
.catch(error => console.error(error));

Output

User deleted: { n: 1, ok: 1, deletedCount: 1 }

Above code deletes one user having the email [email protected].

Conclusion

In conclusion, Mongoose simplifies the interaction with MongoDB by providing a schema-based solution to model our application data. Schemas define the structure and validations for MongoDB documents, while models offer an interface to perform database operations. With built-in validation and query-building methods, Mongoose makes it simple to interact with MongoDB and ensures data integrity across your application. By following the steps outlined in this article, you can effectively define schemas and models in Mongoose for your Node.js applications.


Next Article
Article Tags :

Similar Reads