Files
adastra_api/models/mongo/QcmCategory.js
T
2025-08-08 10:47:29 +02:00

48 lines
1.3 KiB
JavaScript

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);