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

Mongoose के Basics

Mongoose एक library है जो MongoDB driver के ऊपर schemas, validation, और helper methods add करती है।

In this page:

  1. Mongoose Basics
Syntax
javascript
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

javascript
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. #}
आम गलतियां
  1. connect करने से पहले models इस्तेमाल करना
  2. await भूल जाना
  3. यह उम्मीद करना कि 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:

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.