45 lines
1.4 KiB
JavaScript
45 lines
1.4 KiB
JavaScript
![]() |
const mongoose = require('mongoose');
|
||
|
|
||
|
const messageSchema = new mongoose.Schema(
|
||
|
{
|
||
|
conversationId: {
|
||
|
type: mongoose.Schema.Types.ObjectId,
|
||
|
ref: 'Conversation',
|
||
|
required: true,
|
||
|
},
|
||
|
sender: {
|
||
|
type: mongoose.Schema.Types.ObjectId,
|
||
|
ref: 'User',
|
||
|
required: true,
|
||
|
},
|
||
|
// receiver: { // Можно убрать, так как другой участник есть в Conversation.participants
|
||
|
// type: mongoose.Schema.Types.ObjectId,
|
||
|
// ref: 'User',
|
||
|
// required: true,
|
||
|
// },
|
||
|
text: {
|
||
|
type: String,
|
||
|
required: true,
|
||
|
trim: true,
|
||
|
},
|
||
|
readBy: [{ // Массив ID пользователей, прочитавших сообщение (если чат групповой, для 1-на-1 достаточно одного ID)
|
||
|
type: mongoose.Schema.Types.ObjectId,
|
||
|
ref: 'User'
|
||
|
}],
|
||
|
// Или просто флаг для 1-на-1 чата
|
||
|
// isRead: {
|
||
|
// type: Boolean,
|
||
|
// default: false
|
||
|
// }
|
||
|
},
|
||
|
{
|
||
|
timestamps: true, // createdAt (время отправки), updatedAt
|
||
|
}
|
||
|
);
|
||
|
|
||
|
// Индекс для быстрой выборки сообщений по диалогу и сортировки по времени
|
||
|
messageSchema.index({ conversationId: 1, createdAt: -1 });
|
||
|
|
||
|
const Message = mongoose.model('Message', messageSchema);
|
||
|
|
||
|
module.exports = Message;
|