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

Model methods

Models provide create, find, findById, updateOne, deleteOne and more, plus your own instance and 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 return queries you can chain (sort, limit, select, lean) and await. findById, findOne, updateOne and findByIdAndUpdate cover common tasks.

Add instance methods with schema.methods and statics with schema.statics. lean() returns plain objects for faster read-only queries.

Note: Use lean() for read-only queries to skip document hydration.

Example: 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
  1. Forgetting await on queries
  2. Using save when updateOne is enough
  3. Forgetting new: true in findByIdAndUpdate
Chapter Summary
  • create, find, findById, updateOne, deleteOne
  • Chain sort, limit, select, lean
  • schema.methods and statics
  • lean returns plain objects
🔒

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.