- 英文原版
- 关于中文文档
- 快速上手
- 模式(Schemas)
- 模式类型(SchemaTypes)
- 连接(Connections)
- 模型(Models)
- 文档 (Documents)
- 子文档(Subdocuments)
- 查询 (queries)
- 验证 (validation)
- 中间件 (middleware)
- 填充 (Populate)
- 鉴别器 (Discriminators)
- 插件
- AWS Lambda
- API 文档
- Schema
- Connection
- Document
- Model
- Query
- Aggregate
- SchemaType
- VirtualType
- Error
- Version Compatibility
- FAQ
[
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.
const schema = new Schema({ firstName: String, lastName: String });
class PersonClass {
// `fullName` becomes a virtual
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(v) {
const firstSpace = v.indexOf(' ');
this.firstName = v.split(' ')[0];
this.lastName = firstSpace === -1 ? '' : v.substr(firstSpace + 1);
}
// `getFullName()` becomes a document method
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
// `findByFullName()` becomes a static
static findByFullName(name) {
const firstSpace = name.indexOf(' ');
const firstName = name.split(' ')[0];
const lastName = firstSpace === -1 ? '' : name.substr(firstSpace + 1);
return this.findOne({ firstName, lastName });
}
}
schema.loadClass(PersonClass);
var Person = db.model('Person', schema);
Person.create({ firstName: 'Jon', lastName: 'Snow' }).
then(doc => {
assert.equal(doc.fullName, 'Jon Snow');
doc.fullName = 'Jon Stark';
assert.equal(doc.firstName, 'Jon');
assert.equal(doc.lastName, 'Stark');
return Person.findByFullName('Jon Snow');
}).
then(doc => {
assert.equal(doc.fullName, 'Jon Snow');
});