Schema.prototype.loadClass()

Parameters
  • model «Function»
  • [virtualsOnly] «Boolean» if truthy, only pulls virtuals from the class, not methods or statics

Loads an ES6 class into a schema. Maps setters + getters, static methods, and instance methods to schema virtuals, statics, and methods.

Example:

  1. const md5 = require('md5');
  2. const userSchema = new Schema({ email: String });
  3. class UserClass {
  4. // `gravatarImage` becomes a virtual
  5. get gravatarImage() {
  6. const hash = md5(this.email.toLowerCase());
  7. return `https://www.gravatar.com/avatar/${hash}`;
  8. }
  9. // `getProfileUrl()` becomes a document method
  10. getProfileUrl() {
  11. return `https://mysite.com/${this.email}`;
  12. }
  13. // `findByEmail()` becomes a static
  14. static findByEmail(email) {
  15. return this.findOne({ email });
  16. }
  17. }
  18. // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
  19. // and a `findByEmail()` static
  20. userSchema.loadClass(UserClass);