首页 > 解决方案 > 使用 MongoDB 存储通知(连同读取状态)

问题描述

这是用 MongoDB 存储通知的有效方法吗?我想跟踪过去的通知以及通知是否已被用户阅读。

NotificationSchema: {
   title: {type: String, required: true},
   context: {type: String, required: true},
   createdAt: {type: Date, default: Date.now(), required: true},
   readBy: [
      userObjectID: {type: mongoose.Schema.Types.ObjectId, required: true},
      readAt: {type: Date, required: true, default: Date.now()}
   ]
}

我担心的是,当列表变大时,每个用户都必须遍历整个“readBy”字段才能确定用户是否已阅读它。

我是否还应该在 UserSchema 中存储一个记录用户读取的所有通知的字段?

谢谢!任何输入表示赞赏。

标签: node.jsmongodbexpressmongoosemongodb-query

解决方案


您可以考虑创建一个额外的中间模型,如 UserNotification,并从 Notification 中删除 readBy 数组字段。

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const NotificationSchema = new Schema({
  title: { type: String, required: true },
  context: { type: String, required: true },
  createdAt: { type: Date, default: Date.now(), required: true }
});

const UserSchema = new Schema({
  username: { type: String, required: true }
});

const UserNotificationSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  notification: {
    type: Schema.Types.ObjectId,
    ref: "Notification"
  },
  readAt: { type: Date, required: true, default: Date.now() }
});

module.exports = {
  Notification: mongoose.model("Notification", NotificationSchema),
  User: mongoose.model("User", UserSchema),
  UserNotification: mongoose.model("UserNotification", UserNotificationSchema)
};

通过这种设计,添加一个 UserNotification 只需要一个简单的插入到一个集合中,并且我们的 Notification 和 User 模式不会被污染。

但是我们需要在 Notification 和 User 模式上设置虚拟填充,以便能够引用 UserNotification。您可以查看答案以获取如何设置虚拟填充的示例。


推荐阅读