校园论坛已具备基础互动功能,但用户无法感知他人回应,社区活跃度受限。消息通知功能将成为提升用户粘性的关键拼图。

用户无法及时获知帖子的回复与点赞,导致互动链条断裂。消息通知机制将建立完整的反馈闭环,有效增强社区参与感。
初期构想存在误区,误以为需要构建独立私信系统。实际应采用更高效的方式:将通知作为用户行为的自然衍生品。
具体触发场景包括:
该方案的精髓在于:保持核心业务不变,仅追加行为触发的附加动作,延续了"统一出口匿名处理"的设计理念。
const notificationSchema = new mongoose.Schema({
type: {
type: String,
enum: ['comment', 'reply', 'like_post', 'like_comment'],
required: true
},
sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
receiver: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
postId: { type: mongoose.Schema.Types.ObjectId, ref: 'Post', required: true },
commentId: { type: mongoose.Schema.Types.ObjectId, default: null },
isRead: { type: Boolean, default: false }
}, { timestamps: true })
模型包含六个核心字段:
type:区分四种通知类型sender:行为发起者receiver:通知接收者postId:关联的帖子IDcommentId:关联的评论ID(可选)isRead:阅读状态标识采用非侵入式设计,在原有业务接口中追加通知逻辑,避免创建独立接口。
评论接口改造:
// 帖子评论通知作者
if (post.author.toString() !== req.user._id) {
await Notification.create({
type: 'comment', sender: req.user._id,
receiver: post.author, postId: postId
})
}// 评论回复通知原评论者
if (replyTo && 被回复的评论作者 !== 自己) {
await Notification.create({
type: 'reply', sender: req.user._id,
receiver: 被回复的评论作者, postId: postId, commentId: replyToCommentId
})
}
点赞接口改造:
if (被点赞的对象的作者 !== 点赞者) {
await Notification.create({
type: 'like_post', sender: req.user._id,
receiver: post.author, postId: id
})
}
关键原则:禁止自循环通知,通过sender !== receiver校验避免冗余消息。
在全局组件中集成铃铛图标,采用30秒轮询机制获取未读数:
const unreadCount = ref(0)async function fetchUnreadCount() {
const res = await fetch('/api/notifications/unread-count', {
headers: { Authorization: `Bearer ${localStorage.getItem('forum-token')}` }
})
if (res.ok) {
const data = await res.json()
unreadCount.value = data.count
}
}setInterval(fetchUnreadCount, 30000)
通过v-if控制红点显隐,超过99条显示"99+"标识。
独立页面包含以下元素:
点击触发两步操作:标记已读接口调用与帖子跳转。
采用乐观更新策略:先修改本地数据确保即时反馈,再异步提交状态变更请求。
每小时执行自动清理任务,释放数据库存储:
setInterval(async () => {
const result = await Notification.deleteMany({ isRead: true })
if (result.deletedCount > 0) {
console.log(`已自动清理 ${result.deletedCount} 条已读通知`)
}
}, 60 * 60 * 1000)
服务启动时立即执行首次清理。
字段命名不一致
模型使用receiver字段,查询误用user导致数据获取失败。此类问题需重点检查字段映射关系。
状态更新延迟
采用乐观更新方案解决:先更新UI再同步服务端状态,消除等待时间。
消息通知系统成功将离散的互动行为转化为可视化反馈,通过轻量级的事件驱动设计,在不影响核心功能的前提下,显著提升了校园论坛的用户参与度与社区活力。