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

Model के Methods

Models create, find, findById, updateOne, deleteOne, और बाकी देते हैं, साथ में आपके अपने instance और static methods।

In this page:

  1. Model Methods
Syntax
javascript
await Model.find(filter).sort({ field: 1 }).limit(n).lean();
await Model.findById(id);
await Model.updateOne(filter, update);

Model Methods

Query methods queries return करते हैं जिन्हें आप chain (sort, limit, select, lean) और await कर सकते हैं। findById, findOne, updateOne, और findByIdAndUpdate common tasks cover करते हैं।

schema.methods से instance methods और statics से static add करें। lean() faster read-only queries के लिए plain objects return करता है।

Note: document hydration skip करने के लिए read-only queries के लिए lean() इस्तेमाल करें।

उदाहरण: Model methods

javascript
userSchema.methods.greet = function () { return `Hi, ${this.name}`; };
userSchema.statics.findAdults = function () { return this.find({ age: { $gte: 18 } }).sort({ age: -1 }).lean(); };

const adults = await User.findAdults();
const ada = await User.findOne({ name: "Ada" });
console.log(ada.greet());                                   // Hi, Ada
await User.findByIdAndUpdate(ada._id, { $inc: { age: 1 } }, { new: true });
await User.deleteOne({ _id: ada._id });

⚠️ 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. queries पर await भूल जाना
  2. जब updateOne काफी हो save इस्तेमाल करना
  3. findByIdAndUpdate में new: true भूल जाना
चैप्टर सारांश
  • create, find, findById, updateOne, deleteOne jaise methods मिलते हैं
  • sort, limit, select, lean chain करें
  • schema.methods और statics
  • lean plain objects return करता है
🔒

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.