Mongoose के Basics
Mongoose एक library है जो MongoDB driver के ऊपर schemas, validation, और helper methods add करती है।
In this page:
Syntax
const mongoose = require('mongoose');
await mongoose.connect(connectionString);
const Model = mongoose.model('Name', new mongoose.Schema({ field: Type }));
await Model.create({ field: value });
Mongoose Basics
mongoose install करें, mongoose.connect से connect करें, एक Schema define करें और एक Model compile करें। Model से बने documents schema के against validated होते हैं और save और populate जैसे methods पाते हैं।
Mongoose structured applications के लिए popular है और Express के साथ अच्छी तरह integrate होता है।
Note:
Mongoose connect होने तक operations queue करता है, लेकिन आपको फिर भी connect await करना चाहिए।
उदाहरण: Mongoose basics
const mongoose = require("mongoose");
await mongoose.connect(process.env.MONGODB_URI);
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", userSchema);
const ada = await User.create({ name: "Ada", age: 36 });
console.log(ada.name, ada._id instanceof mongoose.Types.ObjectId); // Ada true
⚠️ 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. #}
आम गलतियां
- connect करने से पहले models इस्तेमाल करना
- await भूल जाना
- यह उम्मीद करना कि Mongoose schemaless होगा
चैप्टर सारांश
- mongoose.connect connection खोलता है
- Schema और Model दोनों चाहिए
- Validation और defaults built in हैं
- save और populate add करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: