← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 3 of 7

Schema की परिभाषा

एक Mongoose schema हर field का type और rules declare करता है जैसे required, default, enum, और min।

In this page:

  1. Schema Definition
Syntax
javascript
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

javascript
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. #}
आम गलतियां
  1. यह मान लेना कि unique required की तरह validate करता है
  2. type की array syntax भूल जाना
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.