forked from UKSOURCE/cms.hailearning.edu.vn
79 lines
1.8 KiB
JavaScript
79 lines
1.8 KiB
JavaScript
const mongoose = require('mongoose');
|
|
|
|
// Recent Post model - có thể là view hoặc collection riêng để optimize performance
|
|
const recentPostSchema = new mongoose.Schema({
|
|
title: {
|
|
type: String,
|
|
required: true,
|
|
trim: true
|
|
},
|
|
slug: {
|
|
type: String,
|
|
required: true,
|
|
trim: true
|
|
},
|
|
thumbnail: {
|
|
type: String,
|
|
default: '' // Ảnh nhỏ ở sidebar
|
|
},
|
|
publishedAt: {
|
|
type: String, // "March 26, 2025"
|
|
required: true
|
|
},
|
|
// Reference to original blog post
|
|
originalPostId: {
|
|
type: mongoose.Schema.Types.ObjectId,
|
|
ref: 'Blog',
|
|
required: true
|
|
}
|
|
}, {
|
|
timestamps: true
|
|
});
|
|
|
|
// Indexes
|
|
recentPostSchema.index({ createdAt: -1 });
|
|
recentPostSchema.index({ originalPostId: 1 });
|
|
|
|
// Remove __v from JSON output
|
|
recentPostSchema.set('toJSON', {
|
|
transform: function(doc, ret) {
|
|
delete ret.__v;
|
|
return ret;
|
|
}
|
|
});
|
|
|
|
// Static method to sync with Blog posts
|
|
recentPostSchema.statics.syncFromBlogs = async function(limit = 5) {
|
|
const Blog = require('./blog');
|
|
|
|
// Get recent published blogs
|
|
const recentBlogs = await Blog.find({ status: 'published' })
|
|
.sort({ createdAt: -1 })
|
|
.limit(limit)
|
|
.select('title slug featuredImage publishedAt');
|
|
|
|
// Clear existing recent posts
|
|
await this.deleteMany({});
|
|
|
|
// Create new recent posts
|
|
const recentPosts = recentBlogs.map(blog => ({
|
|
title: blog.title,
|
|
slug: blog.slug,
|
|
thumbnail: blog.featuredImage,
|
|
publishedAt: blog.publishedAt,
|
|
originalPostId: blog._id
|
|
}));
|
|
|
|
if (recentPosts.length > 0) {
|
|
await this.insertMany(recentPosts);
|
|
}
|
|
|
|
return recentPosts;
|
|
};
|
|
|
|
// Static method to get recent posts
|
|
recentPostSchema.statics.getRecent = function(limit = 5) {
|
|
return this.find({}).sort({ createdAt: -1 }).limit(limit);
|
|
};
|
|
|
|
module.exports = mongoose.model('RecentPost', recentPostSchema); |