const mongoose = require('mongoose'); // 检查模型是否已经存在,如果存在则直接返回 if (mongoose.models.Notification) { module.exports = mongoose.models.Notification; return; } const notificationSchema = new mongoose.Schema({ title: { type: String, required: true, trim: true, maxlength: 100 }, content: { type: String, required: true, trim: true, maxlength: 5000 }, type: { type: String, enum: ['info', 'warning', 'success', 'error', 'announcement'], default: 'info' }, priority: { type: String, enum: ['low', 'medium', 'high', 'urgent'], default: 'medium' }, status: { type: String, enum: ['draft', 'published', 'archived'], default: 'draft' }, targetUsers: { type: String, enum: ['all', 'admin', 'vip', 'regular'], default: 'all' }, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, publishDate: { type: Date, default: Date.now }, expiryDate: { type: Date, default: function() { // 默认30天后过期 const date = new Date(); date.setDate(date.getDate() + 30); return date; } }, readBy: [{ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, readAt: { type: Date, default: Date.now } }] }, { timestamps: true }); // 添加索引以提高查询性能 notificationSchema.index({ status: 1, publishDate: -1 }); notificationSchema.index({ targetUsers: 1, status: 1 }); notificationSchema.index({ expiryDate: 1 }, { expireAfterSeconds: 0 }); // TTL索引,过期自动删除 const Notification = mongoose.model('Notification', notificationSchema); module.exports = Notification;