How do I track unread message counts?
Add a read boolean to the Message model. When a user opens a chat, update all unread messages to read: true. Store unreadCount per user in the Conversation model as a Map (userId → count). Increment on new message, reset to 0 when messages are read.
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).
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.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
