var mongoose = require('mongoose'); var User = mongoose.model('User'); var uniqueValidator = require('mongoose-unique-validator'); var slug = require('slug'); var JumpSchema = new mongoose.Schema({ slug: { type: String, lowercase: true, unique: true }, date: { type: Date, default: Date.now }, numero: { type: Number, unique: true }, lieu: String, oaci: String, aeronef: String, imat: String, hauteur: Number, voile: String, taille: Number, categorie: String, module: String, participants: Number, sautants: [String], programme: String, accessoires: String, zone: String, dossier: String, video: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }, {timestamps: true, toJSON: {virtuals: true}}); JumpSchema.plugin(uniqueValidator, { message: 'is already taken' }); JumpSchema.pre('validate', function (next) { if (!this.slug) { this.slugify(); } next(); }); JumpSchema.methods.slugify = function () { this.slug = slug(`${this.numero} ${this.lieu}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36); }; JumpSchema.methods.toJSONFor = function(user){ return { slug: this.slug, date: this.date, numero: this.numero, lieu: this.lieu, oaci: this.oaci, aeronef: this.aeronef, imat: this.imat, hauteur: this.hauteur, voile: this.voile, taille: this.taille, categorie: this.categorie, module: this.module, participants: this.participants, sautants: this.sautants, programme: this.programme, accessoires: this.accessoires, zone: this.zone, dossier: this.dossier, video: this.video, createdAt: this.createdAt, updatedAt: this.updatedAt, author: this.author.toProfileJSONFor(user) }; }; mongoose.model('Jump', JumpSchema);