嗯,这个问题没有正确的答案,但可以肯定的是,你提到的方法根本不是最好的!
首先,当您考虑设计“聊天”模型时,您需要考虑到用户之间会存在数百万条消息,因此当您想要获取聊天时,您需要关心性能。
将消息存储到数组中根本不是一个好主意,您的模型的大小将会很大,并且您必须考虑 MongoDB 的文档大小限制当前为每个文档 16 MB。
https://docs.mongodb.com/manual/reference/limits/ https://docs.mongodb.com/manual/reference/limits/
其次,你必须考虑分页方面,因为当聊天量很大时,它会影响性能,当你检索两个用户之间的聊天时,你不会请求自该时间开始以来的所有聊天,你只会请求最近的聊天,然后如果用户滚动聊天,您可以请求较旧的,这方面非常重要,并且由于其对性能的影响而不能被忽视。
我的方法是将每条消息存储在单独的文档中
首先,将每条消息存储在单个文档中将提高获取聊天记录时的性能,并且文档大小将非常小。
这是一个非常简单的例子,你需要根据你的需要改变模型,它只是为了表达想法:
const MessageSchema = mongoose.Schema({
message:{
text: { type:String, required:true }
// you can add any other properties to the message here.
// for example, the message can be an image ! so you need to tweak this a little
}
// if you want to make a group chat, you can have more than 2 users in this array
users:[{
user: { type:mongoose.Schema.Types.ObjectId, ref:'User', required:true }
}]
sender: { type:mongoose.Schema.Types.ObjectId, ref:'User', required:true },
read: { type:Date }
},
{
timestamps: true
});
您可以通过以下查询获取聊天记录:
Message.find(({ users: { "$in" : [#user1#,#user2#]} })
.sort({ updatedAt: -1 })
.limit(20)
简单又干净!
正如您所看到的,使用这种方法分页变得非常容易。