Implémentation SkydiverId API
This commit is contained in:
+31
-8
@@ -2,22 +2,45 @@ var mongoose = require('mongoose');
|
||||
var uniqueValidator = require('mongoose-unique-validator');
|
||||
var slug = require('slug');
|
||||
|
||||
var QCMSchema = new mongoose.Schema({
|
||||
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' }
|
||||
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmCategory' }
|
||||
]
|
||||
}, {timestamps: true, toJSON: {virtuals: true}});
|
||||
|
||||
QCMSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
||||
QcmSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
||||
|
||||
QCMSchema.methods.toJSONFor = function(){
|
||||
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,
|
||||
categories: this.categories,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt
|
||||
slug: this.slug,
|
||||
categories: this.categories.map(category => category.toJSONFor())
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('QCM', QCMSchema);
|
||||
mongoose.model('Qcm', QcmSchema);
|
||||
|
||||
Reference in New Issue
Block a user