What indexes should I create for the Message model?
Compound index on (senderId, receiverId, createdAt) for efficient message history queries with sorting. Index on (receiverId, read) for finding unread messages. Index on senderId and receiverId individually for user-specific queries.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Chat Message Model and Database Design MongoDB Schema for Chat
senderId (ObjectId ref User), receiverId (ObjectId ref User), text (String, maxLength 1000), read (Boolean, default false), readAt (Date), and timestamps (createdAt, updatedAt from Mongoose schema options).
Yes, if you need a chat list. The Conversation model stores participants (two user IDs), lastMessage (reference to Message), lastMessageAt (for sorting), and unreadCount (Map of userId → count). Update it when a new message is created and when messages are marked as read.
Query Message with $or for both directions (senderId=A receiverId=B OR senderId=B receiverId=A), sort by createdAt -1 (newest first), skip (page-1)*limit, limit. Reverse the result to show oldest first. Use the compound index for efficiency.
Still have questions?
Browse all our FAQs or reach out to our support team
