2020-11-20 10:02:30 +00:00
|
|
|
const mongoose = require('mongoose');
|
|
|
|
const uniqueValidator = require('mongoose-unique-validator');
|
|
|
|
const slug = require('slug');
|
|
|
|
const User = mongoose.model('User');
|
|
|
|
|
|
|
|
const ArticleSchema = new mongoose.Schema(
|
|
|
|
{
|
|
|
|
slug: { type: String, lowercase: true, unique: true },
|
|
|
|
title: String,
|
|
|
|
description: String,
|
|
|
|
body: String,
|
|
|
|
favoritesCount: { type: Number, default: 0 },
|
|
|
|
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
|
|
|
|
tagList: [{ type: String }],
|
|
|
|
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
|
|
|
|
},
|
|
|
|
{ timestamps: true },
|
|
|
|
);
|
|
|
|
|
|
|
|
ArticleSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
|
|
|
|
|
|
|
ArticleSchema.pre('validate', function (next) {
|
|
|
|
if (!this.slug) {
|
2020-04-13 00:02:40 +00:00
|
|
|
this.slugify();
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
2020-11-20 10:02:30 +00:00
|
|
|
ArticleSchema.methods.slugify = function () {
|
|
|
|
this.slug = slug(this.title) + '-' + ((Math.random() * Math.pow(36, 6)) | 0).toString(36);
|
2020-04-13 00:02:40 +00:00
|
|
|
};
|
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
ArticleSchema.methods.updateFavoriteCount = async function () {
|
|
|
|
this.favoritesCount = await User.count({ favorites: { $in: [this._id] } });
|
|
|
|
return await this.save();
|
2020-04-13 00:02:40 +00:00
|
|
|
};
|
|
|
|
|
2020-11-20 10:02:30 +00:00
|
|
|
ArticleSchema.methods.toJSONFor = function (user) {
|
2020-04-13 00:02:40 +00:00
|
|
|
return {
|
|
|
|
slug: this.slug,
|
|
|
|
title: this.title,
|
|
|
|
description: this.description,
|
|
|
|
body: this.body,
|
|
|
|
createdAt: this.createdAt,
|
|
|
|
updatedAt: this.updatedAt,
|
|
|
|
tagList: this.tagList,
|
|
|
|
favorited: user ? user.isFavorite(this._id) : false,
|
|
|
|
favoritesCount: this.favoritesCount,
|
2020-11-20 10:02:30 +00:00
|
|
|
author: this.author.toProfileJSONFor(user),
|
2020-04-13 00:02:40 +00:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
mongoose.model('Article', ArticleSchema);
|