node.js - 使用 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 中存储一个记录用户读取的所有通知的字段?
谢谢!任何输入表示赞赏。
解决方案
您可以考虑创建一个额外的中间模型,如 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。您可以查看此答案以获取如何设置虚拟填充的示例。
推荐阅读
- python - 错误 1452 “无法添加或更新子行”
- c# - CRM 自定义工作流程操作 - 您如何检查已传递的输入参数
- c# - MultiSpeak API:如何将数据库值放入数组中
- reactjs - redux-form 中的“无法读取未定义的属性‘nationalCode’”错误
- typescript - 打字稿不强制或检查返回类型
- excel - Excel/VBA 代码忽略输入的参数
- javascript - 如何从所选元素的属性值中获取对象
- ruby - selenium 页面元素的方法名称和变量之间的名称冲突
- node.js - 使用 Puppeteer 从 localStorage 获取所有值
- java - 如何使用 Jackson 反序列化外部 Lombok 构建器类