How to Use ref in Mongoose Schema for Relationships
In Mongoose, use the
ref option in a schema field to create a reference to another model's document. This allows you to link documents and later populate the referenced data using populate().Syntax
The ref option is used inside a schema field definition to specify which model the field references. It works together with the type set to Schema.Types.ObjectId, which stores the ID of the referenced document.
- type: Must be
Schema.Types.ObjectIdto store the reference ID. - ref: The name of the model you want to reference.
javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const exampleSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User' } });
Example
This example shows how to define two schemas, User and Post, where each post references a user by their ID. Then it demonstrates how to populate the user data when querying posts.
javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // User schema const userSchema = new Schema({ name: String }); const User = mongoose.model('User', userSchema); // Post schema with ref to User const postSchema = new Schema({ title: String, author: { type: Schema.Types.ObjectId, ref: 'User' } }); const Post = mongoose.model('Post', postSchema); async function run() { await mongoose.connect('mongodb://localhost:27017/testdb'); // Create a user const user = await User.create({ name: 'Alice' }); // Create a post referencing the user const post = await Post.create({ title: 'Hello World', author: user._id }); // Find post and populate author details const result = await Post.findById(post._id).populate('author').exec(); console.log(result); await mongoose.disconnect(); } run();
Output
{
_id: <ObjectId>,
title: 'Hello World',
author: {
_id: <ObjectId>,
name: 'Alice',
__v: 0
},
__v: 0
}
Common Pitfalls
- Not setting the
typetoSchema.Types.ObjectIdwhen usingrefcauses errors or unexpected behavior. - Forgetting to call
populate()when querying means you only get the referenced ID, not the full document. - Using the wrong model name in
refwill prevent Mongoose from finding the referenced documents.
javascript
const wrongSchema = new Schema({ author: { type: String, ref: 'User' } // Wrong: type should be ObjectId }); // Correct way: const correctSchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'User' } });
Quick Reference
| Property | Description | Example |
|---|---|---|
| type | Data type of the field, must be ObjectId for references | type: Schema.Types.ObjectId |
| ref | Name of the model to reference | ref: 'User' |
| populate() | Method to fetch referenced documents | Post.find().populate('author') |
Key Takeaways
Use type Schema.Types.ObjectId with ref to link documents in Mongoose schemas.
The ref value must match the target model name exactly.
Use populate() to retrieve full referenced documents instead of just IDs.
Incorrect type or ref causes errors or missing data in queries.
References enable easy relationships between collections in MongoDB.