Creating from ES6 Classes Using loadClass() - 图1mongoose

Creating from ES6 Classes Using loadClass() - 图2mongoose

[

Creating from ES6 Classes Using loadClass() ](#creating-from-es6-classes-using-loadclass)

Mongoose allows creating schemas from ES6 classes. The loadClass() function lets you pull in methods, statics, and virtuals from an ES6 class. A class method maps to a schema method, a static method maps to a schema static, and getters/setters map to virtuals.

  1. const schema = new Schema({ firstName: String, lastName: String });
  2. class PersonClass {
  3. // `fullName` becomes a virtual
  4. get fullName() {
  5. return `${this.firstName} ${this.lastName}`;
  6. }
  7. set fullName(v) {
  8. const firstSpace = v.indexOf(' ');
  9. this.firstName = v.split(' ')[0];
  10. this.lastName = firstSpace === -1 ? '' : v.substr(firstSpace + 1);
  11. }
  12. // `getFullName()` becomes a document method
  13. getFullName() {
  14. return `${this.firstName} ${this.lastName}`;
  15. }
  16. // `findByFullName()` becomes a static
  17. static findByFullName(name) {
  18. const firstSpace = name.indexOf(' ');
  19. const firstName = name.split(' ')[0];
  20. const lastName = firstSpace === -1 ? '' : name.substr(firstSpace + 1);
  21. return this.findOne({ firstName, lastName });
  22. }
  23. }
  24. schema.loadClass(PersonClass);
  25. var Person = db.model('Person', schema);
  26. Person.create({ firstName: 'Jon', lastName: 'Snow' }).
  27. then(doc => {
  28. assert.equal(doc.fullName, 'Jon Snow');
  29. doc.fullName = 'Jon Stark';
  30. assert.equal(doc.firstName, 'Jon');
  31. assert.equal(doc.lastName, 'Stark');
  32. return Person.findByFullName('Jon Snow');
  33. }).
  34. then(doc => {
  35. assert.equal(doc.fullName, 'Jon Snow');
  36. });