Model methods
Models provide create, find, findById, updateOne, deleteOne and more, plus your own instance and static methods.
In this page:
Syntax
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
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
- Forgetting await on queries
- Using save when updateOne is enough
- 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: