Mongoose : Models and Relationships

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:02:00

Mongoose

Mongoose is a complex Node.js module for MongoDB Object Data Modelling (ODM). It offers a basic schema-based approach to modeling application data.

Mongoose: Models

Mongoose models are constructors created from Schema specifications. They represent documents that may be stored and retrieved from MongoDB collections.

Defining Models

In Mongoose, models are built with mongoose.model(), whereas schemas define document structure. These models encapsulate document attributes and behaviors, making it easier to manipulate and interact with MongoDB databases. 

Interacting with Models

Models support CRUD actions such as create(), find(), findOne(), update(), and delete(). These methods provide easy access to data in the related MongoDB collection.

  • create(): Models enable the addition of new documents to the database collection.
  • find(): They allow for the retrieval of several documents from a collection depending on specific criteria.
  • findOne(): This function returns a single document from the collection that meets the requirements specified.
  • update(): Models let you update existing documents in the collection with new data or updates.
  • delete(): They enable the removal of documents from a collection based on defined requirements, either individually or in bulk.

Schema

Models are constructed by compiling Schema definitions. A schema specifies the organization of documents in a collection, including their fields and types.

Types of Relationships

Mongoose supports various types of relationships between models:

  • One-to-One Relationship
  • One-to-Many Relationship
  • Many-to-Many Relationship

One-to-One Relationship

A one-to-one relationship means that each document in one collection is only linked to one document in another.

One-to-Many Relationship

A one-to-many relationship means that any document in one collection can be linked to one or more documents in another.

Many-to-Many Relationship

A many-to-many relationship means that each document in one collection can be linked to one or more documents in another, and vice versa.

Population of Relationships

In Mongoose, population is the process of filling reference fields in a document with data from another collection. It creates relationships between models by replacing stored references with their associated documents during queries.

Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this