var mongoose = require('mongoose'); var uniqueValidator = require('mongoose-unique-validator'); var slug = require('slug'); var QcmSchema = new mongoose.Schema({ name: { type: String, lowercase: true, unique: true }, slug: { type: String, lowercase: true, unique: true }, categories: [ { type: mongoose.Schema.Types.ObjectId, ref: 'QcmCategory' } ] }, {timestamps: true, toJSON: {virtuals: true}}); QcmSchema.plugin(uniqueValidator, { message: 'is already taken' }); QcmSchema.pre('validate', function (next) { if (!this.slug) { this.slugify(); } next(); }); QcmSchema.methods.slugify = function () { this.slug = slug(`${this.name}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36); }; QcmSchema.methods.addCategory = function (id) { if (this.categories.indexOf(id) === -1) { this.categories.push(id); } return this.save(); }; QcmSchema.methods.removeCategory = function (id) { this.categories.remove(id); return this.save(); }; QcmSchema.methods.toJSONFor = function() { return { name: this.name, slug: this.slug, categories: this.categories.map(category => category.toJSONFor()) }; }; mongoose.model('Qcm', QcmSchema);