Jab aap ek Ecommerce website banate hain, toh aapko “Products”, “Orders”, aur “Users” ke beech connection banana padta hai. Mongoose mein ye kaam mongoose.Schema.Types.ObjectId aur ref ke zariye hota hai.
Chaliye is code snippet ko step-by-step todte hain:
JavaScript
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
}
1. type: mongoose.Schema.Types.ObjectId
MongoDB har document ko ek unique pehchan deta hai jise hum _id kehte hain. Iska format kuch aisa dikhta hai: 64f1a2b3c4d5e6f7g8h9i0j1.
- Matlab: Jab hum
typekoObjectIdrakhte hain, toh hum Mongoose ko bata rahe hain ki is field mein koi normal String ya Number nahi aayega, balki kisi dusre document ki Unique ID store hogi.
2. ref: "User" (The Reference)
Ye sabse important part hai. ref ka matlab hai Reference.
- Matlab: Ye Mongoose ko batata hai ki ye ID kis “Collection” (Table) se taluq rakhti hai.
- Fayda: Iska use karke hum
.populate()method chala sakte hain. Isse humein sirf ID nahi, balki us User ka pura data (Name, Email, Address) mil jata hai bina doosri query likhe.
3. required: true
- Matlab: Iska matlab hai ki ye field khali nahi ho sakti.
- Ecommerce Example: Bina User ke koi “Order” ya “Review” create nahi ho sakta. Isliye
userIdhona lazmi hai.
4. Real-World Example: Ye Kaam Kaise Karta Hai?
Sochiye aapke paas ek Order Schema hai. Usme aapne userId ko upar waale tarike se define kiya hai.
Database mein data aisa dikhega:
JSON
{
"_id": "order_999",
"product": "iPhone 15",
"userId": "64f1a2b3c4d5..." // Sirf ID store hui
}
Code mein data fetch karte waqt:
Jab aap .populate('userId') use karenge, toh Mongoose automatically “User” collection mein jayega aur wo ID dhoond kar pura data le aayega:
JavaScript
const order = await Order.findById("order_999").populate("userId");
console.log(order.userId.name); // Output: "Rahul Kumar"
5. Blog Summary Table
| Property | Kaam | Kyun Zaroori Hai? |
| ObjectId | Unique Identification | Data ko connect karne ke liye unique key hai. |
| ref | Linking Collections | Batata hai ki ID kis table (e.g., User, Product) ki hai. |
| Populate | Data Merging | Ek hi query mein do tables ka data jodne ke liye. |