Created
June 28, 2017 10:03
-
-
Save TaijaQ/fbbdc549c6893dab3f9383f3095d9f93 to your computer and use it in GitHub Desktop.
Advanced schema creation with ES6
From http://mongoosejs.com/docs/advanced_schemas.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment