Created
July 5, 2018 19:45
-
-
Save KelvinCampelo/254924241ce8156f86e38d5fdfdd572c to your computer and use it in GitHub Desktop.
A Mongoose Schema/Model example using ES6
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
import mongoose, { Schema } from 'mongoose'; | |
const peopleSchema = new Schema( | |
{ | |
firstName: { | |
type: String, | |
required: true, | |
trim: true | |
}, | |
lastName: { | |
type: String, | |
required: true, | |
trim: true | |
}, | |
birthday: { | |
type: Date | |
}, | |
activated: { | |
type: Boolean, | |
default: true | |
} | |
}, | |
{ | |
timestamps: true, | |
toJSON: { | |
virtuals: true, | |
transform: (obj, ret) => { | |
delete ret._id; | |
delete ret.__v; | |
} | |
} | |
} | |
); | |
peopleSchema.methods = { | |
view(full) { | |
const view = { | |
id: this.id, | |
fullName: `${this.firstName} ${this.lastName}`, | |
age: this.age | |
}; | |
return full | |
? { | |
...view, | |
birthday: this.birthday, | |
activated: this.activated, | |
createdAt: this.createdAt, | |
updatedAt: this.updatedAt | |
} | |
: view; | |
} | |
}; | |
peopleSchema.virtual('age').get(function() { | |
var birthday = +new Date(this.birthday); | |
return ~~((Date.now() - birthday) / 31557600000); | |
}); | |
const model = mongoose.model('People', peopleSchema); | |
export const schema = model.schema; | |
export default model; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment