শেষ lesson-এর মৌলিক field নিয়মের বাইরে, Mongoose সমৃদ্ধ validation আর referenced document নিয়ে কাজ করার একটা পরিষ্কার উপায় সমর্থন করে।
const productSchema = new Schema({
name: { type: String, required: true, minlength: 2, maxlength: 100 },
price: { type: Number, required: true, min: 0 },
category: { type: String, enum: ["electronics", "books", "clothing"] }
})একটা validate function আপনার নিজের logic চালায় আর true বা false return করে:
const userSchema = new Schema({
email: {
type: String,
required: true,
validate: {
validator: (value) => /^.+@.+\..+$/.test(value),
message: "একটা বৈধ email address লিখুন"
}
}
})অন্য একটা model reference করতে — schema-design lesson-এর "referencing" pattern — একটা field-এর type Schema.Types.ObjectId-এ set করুন আর ref-কে target model-এর নামের দিকে point করুন:
const postSchema = new Schema({
title: { type: String, required: true },
author: { type: Schema.Types.ObjectId, ref: "User" }
})populate() ছাড়া, একটা query author field-এ শুধু raw ObjectId return করে। .populate("author") call করা এটাকে সম্পূর্ণ referenced document দিয়ে প্রতিস্থাপন করে — একটা সরল API সহ aggregation pipeline-এ $lookup যে একই result তৈরি করে:
const post = await Post.findOne({ title: "Getting Started" }).populate("author")
console.log(post.author.name)
// "Rahul Verma" — সম্পূর্ণ User document এখন attachedpopulate() বনাম $lookup — ভিন্ন trade-off
populate() পর্দার আড়ালে একটা আলাদা query হিসেবে চলে, database-এর ভিতরে না বরং application code-এ join করা — সরল ক্ষেত্রে এটা ঠিক আছে আর পড়তে অনেক সহজ; বড় collection জুড়ে জটিল reporting query-র জন্য, aggregation pipeline-এর $lookup সাধারণত দ্রুত পছন্দ।