Files
cms.uldp.edu.vn/models/blogComment.js

104 lines
2.3 KiB
JavaScript

const mongoose = require('mongoose');
const blogCommentSchema = new mongoose.Schema({
postId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Blog',
required: true
},
authorName: {
type: String,
required: true,
trim: true // "Frank Flores"
},
authorEmail: {
type: String,
default: '',
trim: true
},
authorPhone: {
type: String,
default: '',
trim: true
},
authorAddress: {
type: String,
default: '',
trim: true
},
authorDate: {
type: String,
default: '',
trim: true
},
authorAvatar: {
type: String,
default: '' // "/assets/img/inner-page/news-details/comment-1.png"
},
content: {
type: String,
required: true,
trim: true
},
parentId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'BlogComment',
default: null // Cho threaded comments (reply)
},
status: {
type: String,
enum: ['pending', 'approved', 'rejected'],
default: 'pending'
}
}, {
timestamps: true // Vẫn giữ timestamps cho admin quản lý
});
// Indexes
blogCommentSchema.index({ postId: 1, status: 1, createdAt: -1 });
blogCommentSchema.index({ parentId: 1 });
blogCommentSchema.index({ status: 1 });
// Remove __v from JSON output
blogCommentSchema.set('toJSON', {
transform: function(doc, ret) {
delete ret.__v;
return ret;
}
});
// Static methods
blogCommentSchema.statics.getApprovedByPost = function(postId) {
return this.find({
postId: postId,
status: 'approved',
parentId: null // Chỉ lấy comments gốc, không lấy replies
}).sort({ createdAt: -1 });
};
blogCommentSchema.statics.getReplies = function(parentId) {
return this.find({
parentId: parentId,
status: 'approved'
}).sort({ createdAt: 1 }); // Replies sắp xếp theo thời gian tăng dần
};
blogCommentSchema.statics.getByStatus = function(status) {
return this.find({ status: status })
.populate('postId', 'title slug')
.sort({ createdAt: -1 });
};
// Method to approve comment
blogCommentSchema.methods.approve = function() {
this.status = 'approved';
return this.save();
};
// Method to reject comment
blogCommentSchema.methods.reject = function() {
this.status = 'rejected';
return this.save();
};
module.exports = mongoose.model('BlogComment', blogCommentSchema);