MongoDBIntermediate
Population (Relationship)
ObjectId reference আর populate() দিয়ে related document আনা — select, match, nested populate — বাংলায়।
11টি অংশবাংলা ভাষায়
Populate কী?
MongoDB-তে related document পুরোটা save থাকে না — শুধু ObjectId reference রাখা হয়। `populate()` সেই reference দেখে কাজ করে সম্পর্কিত document-গুলো আবার ভরে তোলে — এক query-তেই।
Reference schema
ref দিয়ে সম্পর্কjs
js
const postSchema = new mongoose.Schema({
title: String,
body: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "Comment" }],
});populate() ব্যবহার
Basic populatejs
js
// author-এ ObjectId নয় — পুরো User document
const posts = await Post.find().populate("author");
// শুধু কয়েকটি field + match + nested populate
const result = await Post.find()
.populate({
path: "author",
select: "name email", // শুধু এই field-গুলো
match: { isActive: true },
})
.populate({
path: "comments",
options: { sort: { createdAt: -1 }, limit: 20 },
});
console.log(posts[0].author.name); // এখন populatedNested populate
দুই স্তরের populatejs
js
// comment-এ author আবার populate
const posts = await Post.find().populate({
path: "comments",
populate: { path: "author", select: "name" },
});
// populate করা field আবার populate — unlimited
await Order.find().populate({
path: "items.product", // array of refs
});populate string vs object
| কাজ | উদাহরণ |
|---|---|
| শুধু populate | .populate("author") |
| নির্দিষ্ট field | .populate({ path: "author", select: "name" }) |
| শর্তসহ | .populate({ path: "author", match: { isActive: true } }) |
| সীমা সহ | .populate({ path: "comments", options: { limit: 5 } }) |
| Nested | .populate({ path: "comments", populate: { path: "author" } }) |
N+1 সমস্যা এড়ান
লুপের ভেতরে একেক document-এর জন্য একেক query না চালিয়ে (N+1) একবারেই populate() ব্যবহার করুন — request প্রতি DB hit অনেক কমে যায়।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।