AllenYuan

article model

May 10th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var mongoose = require('mongoose');
  2. var uniqueValidator = require('mongoose-unique-validator');
  3. var slug = require('slug'); // package for auto-creating URL slugs
  4.  
  5. var ArticleSchema = new mongoose.Schema({
  6.   slug: {type: String, lowercase: true, unique: true},
  7.   title: String,
  8.   description: String,
  9.   body: String,
  10.   favoritesCount: {type: Number, default: 0},
  11.   tagList: [{type: String}],
  12.   author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
  13. }, {timestamps: true});
  14.  
  15. // validate the slug is unique
  16. ArticleSchema.plugin(uniqueValidator, {message: 'is already taken'});
  17.  
  18. // convert article title to a slug
  19. ArticleSchema.methods.slugify = function() {
  20.   this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
  21. }
  22.  
  23. // generate slug before validation
  24. ArticleSchema.pre('validate', function(next) {
  25.   if (!this.slug) {
  26.     this.slugify();
  27.   }
  28.   next();
  29. });
  30.  
  31. // return the data of our article
  32. ArticleSchema.methods.toJSONFor = function(user) {
  33.   return {
  34.     slug: this.slug,
  35.     title: this.title,
  36.     description: this.description,
  37.     body: this.body,
  38.     createdAt: this.createdAt,
  39.     updatedAt: this.updatedAt,
  40.     tagList: this.tagList,
  41.     favoritesCount: this.favoritesCount,
  42.     author: this.author.toProfileJSONFor(user)
  43.   };
  44. };
  45.  
  46. mongoose.model('Article', ArticleSchema);
Advertisement
Add Comment
Please, Sign In to add comment