{"size": 1498, "ext": "js", "max_stars_repo_path": "server/src/models/Post.js", "max_stars_repo_name": "Darkzarich/Smiler", "max_stars_repo_stars_event_min_datetime": "2019-09-19T15:54:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T18:34:22.000Z", "max_issues_repo_path": "server/src/models/Post.js", "max_issues_repo_name": "Darkzarich/express-blog", "max_issues_repo_issues_event_min_datetime": "2019-09-19T15:53:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-30T10:27:51.000Z", "max_forks_repo_path": "server/src/models/Post.js", "max_forks_repo_name": "Darkzarich/Smiler", "max_forks_repo_forks_event_min_datetime": "2020-02-02T16:06:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-02T16:06:51.000Z"}
{"max_stars_count": 3, "max_issues_count": 5, "max_forks_count": 1, "avg_line_length": 17.6235294118, "max_line_length": 52, "alphanum_fraction": 0.5894526035}
/* eslint-disable no-underscore-dangle */
/* eslint-disable func-names */
const mongoose = require('mongoose');

const { Schema } = mongoose;

const schema = new Schema({
  title: {
    type: String,
    required: true,
  },
  slug: {
    type: String,
  },
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  },
  tags: [
    {
      type: Schema.Types.String,
    },
  ],
  sections: [
    {
      type: Schema.Types.Mixed,
    },
  ],
  commentCount: {
    type: Number,
    default: 0,
  },
  rating: {
    type: Number,
    default: 0,
  },
}, {
  timestamps: true,
});

schema.static('commentCountInc', function (postId) {
  return this.findByIdAndUpdate(postId, {
    $inc: { commentCount: 1 },
  }, {
    new: true,
  });
});

schema.static('commentCountDec', function (postId) {
  return this.findByIdAndUpdate(postId, {
    $inc: { commentCount: -1 },
  }, {
    new: true,
  });
});

schema.methods.toResponse = function (user) {
  const rated = user ? user.isRated(this.id) : {};

  return {
    title: this.title,
    sections: this.sections,
    slug: this.slug,
    author: this.author,
    uploads: this.uploads,
    id: this._id,
    commentCount: this.commentCount,
    rating: this.rating,
    createdAt: this.createdAt,
    tags: this.tags,
    rated: {
      isRated: rated.result || false,
      negative: rated.negative || false,
    },
  };
};

schema.set('toJSON', {
  virtuals: true,
  versionKey: false,
});


module.exports = mongoose.model('Post', schema);
