2020-04-13 00:02:40 +00:00
|
|
|
var mongoose = require('mongoose');
|
|
|
|
var uniqueValidator = require('mongoose-unique-validator');
|
|
|
|
var slug = require('slug');
|
|
|
|
var User = mongoose.model('User');
|
2020-08-14 10:37:34 +00:00
|
|
|
var TrackData = mongoose.model('TrackData');
|
2020-04-13 00:02:40 +00:00
|
|
|
|
|
|
|
var TrackSchema = new mongoose.Schema({
|
|
|
|
slug: {type: String, lowercase: true, unique: true},
|
|
|
|
title: String,
|
|
|
|
description: String,
|
|
|
|
body: String,
|
2020-08-28 19:50:53 +00:00
|
|
|
visible: Boolean,
|
2020-04-13 00:02:40 +00:00
|
|
|
numEvents: {type: Number, default: 0},
|
2020-04-14 01:05:07 +00:00
|
|
|
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
|
|
|
|
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
|
2020-08-14 10:37:34 +00:00
|
|
|
trackData: { type: mongoose.Schema.Types.ObjectId, ref: 'TrackData' },
|
2020-04-13 00:02:40 +00:00
|
|
|
}, {timestamps: true});
|
|
|
|
|
|
|
|
TrackSchema.plugin(uniqueValidator, {message: 'is already taken'});
|
|
|
|
|
|
|
|
TrackSchema.pre('validate', function(next){
|
|
|
|
if(!this.slug) {
|
|
|
|
this.slugify();
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
TrackSchema.methods.slugify = function() {
|
|
|
|
this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
|
|
|
};
|
|
|
|
|
|
|
|
TrackSchema.methods.toJSONFor = function(user){
|
|
|
|
return {
|
|
|
|
slug: this.slug,
|
|
|
|
title: this.title,
|
|
|
|
description: this.description,
|
|
|
|
createdAt: this.createdAt,
|
|
|
|
updatedAt: this.updatedAt,
|
2020-08-16 21:23:18 +00:00
|
|
|
visibleForAll: this.author ? this.author.areTracksVisibleForAll : false,
|
2020-08-28 19:50:53 +00:00
|
|
|
visible: this.visible,
|
2020-04-13 00:02:40 +00:00
|
|
|
author: this.author.toProfileJSONFor(user)
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
mongoose.model('Track', TrackSchema);
|