Schema.prototype.pre()

Parameters
  • The «String|RegExp» method name or regular expression to match method name

  • [options] «Object»

  • [options.document] «Boolean» If name is a hook for both document and query middleware, set to true to run on document middleware. For example, set options.document to true to apply this hook to Document#deleteOne() rather than Query#deleteOne().

  • [options.query] «Boolean» If name is a hook for both document and query middleware, set to true to run on query middleware.

  • callback «Function»

Defines a pre hook for the model.

Example

  1. const toySchema = new Schema({ name: String, created: Date });
  2. toySchema.pre('save', function(next) {
  3. if (!this.created) this.created = new Date;
  4. next();
  5. });
  6. toySchema.pre('validate', function(next) {
  7. if (this.name !== 'Woody') this.name = 'Woody';
  8. next();
  9. });
  10. // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
  11. toySchema.pre(/^find/, function(next) {
  12. console.log(this.getFilter());
  13. });
  14. // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
  15. toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
  16. console.log(this.getFilter());
  17. });
  18. toySchema.pre('deleteOne', function() {
  19. // Runs when you call `Toy.deleteOne()`
  20. });
  21. toySchema.pre('deleteOne', { document: true }, function() {
  22. // Runs when you call `doc.deleteOne()`
  23. });