Mongoose
Schema
Model
MongoDB
Database

Mongoose Schema vs Model?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Mongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model application data, enforcing structure within the documents and giving us powerful capabilities to perform validations, queries, transformations, and more. Understanding Mongoose involves familiarizing oneself with two vital aspects: the Schema and the Model. Let's dive into each of these components in detail.

Schema in Mongoose

A Schema in Mongoose defines the structure of a document, the default values, validators, and utility methods. It is a blueprint for the data structure that provides a comprehensive overview of what your MongoDB collections will look like.

Creating a Schema

A Mongoose Schema specifies the fields and types, much like a definition in a strongly typed language. Below is an example of a Schema for a collection of User documents:

javascript
1const mongoose = require('mongoose');
2const Schema = mongoose.Schema;
3
4const userSchema = new Schema({
5  name: {
6    type: String,
7    required: true,
8    minlength: 2,
9    maxlength: 50
10  },
11  email: {
12    type: String,
13    required: true,
14    unique: true,
15    match: /.+\@.+\..+/
16  },
17  password: {
18    type: String,
19    required: true
20  },
21  registeredAt: {
22    type: Date,
23    default: Date.now
24  }
25});

Key Features of Schemas

  • Type Declaration: Every field within a Schema is defined with a type.
  • Validation: Mongoose provides built-in validators like required, minlength, maxlength, match, etc.
  • Default Values: The default option allows setting default values for fields.
  • Custom Validators: You can define custom validation logic for any field.

Schema Methods & Statics

Schemas allow the definition of custom methods and static functions that add functionality directly to the document or model level.

  • Instance Methods: Are applied to individual document instances.
javascript
  userSchema.methods.getFullName = function() {
    return `${this.firstName} ${this.lastName}`;
  };
  • Static Methods: Are attached to the model itself, enabling broader operations.
javascript
  userSchema.statics.findByEmail = function(email) {
    return this.findOne({ email });
  };

Model in Mongoose

A Model is a constructor compiled from the Schema definitions. It represents a collection of documents in the database and provides an interface to interact with the database.

Creating a Model

Once a Schema is defined, a Model can be created using the mongoose.model function. Here's how you can create a model from the userSchema:

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

Utilizing a Model

With the Model, you can perform various database operations. Here are some common operations:

  • Creating Documents:
javascript
1  const newUser = new User({
2    name: 'John Doe',
3    email: '[email protected]',
4    password: 'securepassword123'
5  });
6  newUser.save()
7    .then(user => console.log(user))
8    .catch(error => console.log(error));
  • Querying:
javascript
  User.find({ name: 'John Doe' })
    .then(users => console.log(users))
    .catch(error => console.log(error));
  • Updating:
javascript
  User.updateOne({ email: '[email protected]' }, { name: 'Jonathan Doe' })
    .then(result => console.log(result))
    .catch(error => console.log(error));
  • Deleting:
javascript
  User.deleteOne({ email: '[email protected]' })
    .then(result => console.log(result))
    .catch(error => console.log(error));

Key Points of Mongoose Models

  • Inherits from Document: Every instance of a Model is a fully functional document.
  • Operations on Collection: Provides CRUD operations for documents on a MongoDB collection.
  • Middleware: Models support pre and post hooks, enabling logic execution during lifecycle events.

Schema vs Model - A Summarized Comparison

FeatureSchemaModel
DefinitionBlueprint for database documents (structure, validations).Interface for CRUD operations, constructed from a schema.
PurposeDictates structure and provides methods/utility methods.Handles data manipulation and interacts with the database.
MethodsCustom instance methods and static functions can be added.Built with instance methods and modeling operations.
CreationDefined using mongoose.Schema.Created with mongoose.model.
UsagePrimarily used for creating a Model.Used for querying, updating, and deleting documents.

Conclusion

Understanding the distinction between Schemas and Models in Mongoose is crucial for effectively modeling MongoDB collections in a Node.js application. Schemas provide structure, default settings, and validation for documents, whereas Models serve as the primary interface for interacting with documents in the database. Recognizing their roles helps implement a robust and maintainable database layer, aligning data handling with application logic seamlessly.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.