Skip to main content

One post tagged with "schema relationship"

View All Tags

· 4 min read
Sivabharathy

Mongoose provides a powerful way to model relationships between documents in your MongoDB collections. Here's an explanation of Mongoose populate with examples for one-to-one, one-to-many, and many-to-many relationships:

1. One-to-One Relationship:

This represents a scenario where a document in one collection can have a reference to at most one document in another collection. Here's an example:

  • User Schema:
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: String,
profile: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Profile' // Reference to the Profile model
}
});

module.exports = mongoose.model('User', userSchema);