Schema की परिभाषा
एक Mongoose schema हर field का type और rules declare करता है जैसे required, default, enum, और min।
In this page:
Syntax
const schema = new mongoose.Schema({
field: { type: Type, required: true, default: value },
other: String
});
Schema Definition
Fields एक type या required, default, unique, enum, min, max, match, और custom validators वाला एक options object accept करती हैं।
timestamps option createdAt और updatedAt add करता है। Sub-schemas structured data embed करते हैं और arrays lists hold करते हैं।
unique option validate करने की बजाय एक index बनाता है।
Note:
unique एक index बनाता है; यह एक validator नहीं है, इसलिए duplicate key errors handle करें।
उदाहरण: Schema definition
const productSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true },
price: { type: Number, min: 0, default: 0 },
category: { type: String, enum: ["office", "home", "toys"] },
tags: [String],
sku: { type: String, unique: true },
}, { timestamps: true });
const Product = mongoose.model("Product", productSchema);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- यह मान लेना कि unique required की तरह validate करता है
- type की array syntax भूल जाना
- timestamps skip करना
चैप्टर सारांश
- Options के साथ Types
- required, default, enum, min, max jaise options मिलते हैं
- timestamps dates add करता है
- unique एक index बनाता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: