How do I load chat message history with pagination?
REST endpoint GET /api/chat/:targetUserId?page=1&limit=50. Query Message with $or for both directions, sort by createdAt -1, skip (page-1)*limit, limit. Return messages reversed (oldest first) with pagination metadata (total, totalPages, hasMore). Use compound index on (senderId, receiverId, createdAt) for efficiency.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Chat Message Persistence and History Loading and Paginating Messages
On scroll to top, load the next page of older messages and prepend to the list. Maintain scroll position by saving the previous scrollHeight and setting scrollTop after new messages are added. Stop loading when hasMore is false.
In the message:send handler, save to MongoDB with Message.create(), update the Conversation model (lastMessage, lastMessageAt, unreadCount), then broadcast to the room via io.to(roomId).emit('message:received', message). Use a callback acknowledgment to confirm success.
GET /api/chat (chat list with unread counts), GET /api/chat/:targetUserId (message history with pagination), PATCH /api/chat/read/:targetUserId (mark messages as read). Use Socket.io for real-time new messages and typing indicators. REST handles initial load, Socket.io handles live updates.
Still have questions?
Browse all our FAQs or reach out to our support team
