【问题标题】:Storing Notification with MongoDB (along with read status)使用 MongoDB 存储通知(连同读取状态)
【发布时间】:2020-06-15 02:33:33
【问题描述】:

这是一种使用 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.js mongodb express mongoose mongodb-query


    【解决方案1】:

    您可以考虑创建一个额外的中间模型,如 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 架构上设置 virtual populate 才能引用 UserNotification。您可以查看this 答案,了解如何设置虚拟填充的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2019-10-24
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 2015-12-21
      • 2019-12-29
      相关资源
      最近更新 更多