Implémentation SkydiverId API
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
var mongoose = require('mongoose');
|
||||
var uniqueValidator = require('mongoose-unique-validator');
|
||||
var slug = require('slug');
|
||||
|
||||
var QcmCategorySchema = new mongoose.Schema({
|
||||
num: Number,
|
||||
name: { type: String, unique: true },
|
||||
slug: { type: String, lowercase: true, unique: true },
|
||||
questions: [
|
||||
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmQuestion' }
|
||||
]
|
||||
}, {timestamps: true, toJSON: {virtuals: true}});
|
||||
|
||||
QcmCategorySchema.plugin(uniqueValidator, { message: 'is already taken' });
|
||||
|
||||
QcmCategorySchema.pre('validate', function (next) {
|
||||
if (!this.slug) {
|
||||
this.slugify();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
QcmCategorySchema.methods.slugify = function () {
|
||||
this.slug = slug(`${this.name}-${this.num}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
};
|
||||
|
||||
QcmCategorySchema.methods.addQuestion = function (id) {
|
||||
if (this.questions.indexOf(id) === -1) {
|
||||
this.questions.push(id);
|
||||
}
|
||||
return this.save();
|
||||
};
|
||||
|
||||
QcmCategorySchema.methods.removeQuestion = function (id) {
|
||||
this.questions.remove(id);
|
||||
return this.save();
|
||||
};
|
||||
|
||||
QcmCategorySchema.methods.toJSONFor = function() {
|
||||
return {
|
||||
num: this.num,
|
||||
name: this.name,
|
||||
slug: this.slug,
|
||||
questions: this.questions.map(question => question.toJSONFor())
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('QcmCategory', QcmCategorySchema);
|
||||
Reference in New Issue
Block a user