DEV Community

Ali Hamza
Ali Hamza

Posted on

Day 170 of Learning MERN Stack

Hello Dev Community! 👋

It is officially Day 170 of my full-stack engineering track! Today, I designed and implemented the backend message retrieval and chat history processing endpoints (getUserforSidebar & getMessages) for QuickChat using Node.js, Express, and MongoDB! ⚙️💬

Here is how I structured the database queries for chat retrieval and read receipts.


🛠️ Technical Breakdown: Message Fetching & Unseen Counters

As captured in my implementation snapshots (messageController.js):

1. Dynamic User Discovery & Parallel Unseen Counting

  • Filtered out the currently logged-in user using Mongoose $ne operator while stripping out password projections.
  • Used Promise.all alongside map iterations to asynchronously gather unread message counts per user card:

javascript
  const filteredUser = await user.find({ _id: { $ne: userId } }).select("-password");

  const promise = filteredUser.map(async (user) => {
    const messages = await message.find({ senderId: user._id, receiverId: userId, seen: false });
    if (messages.length > 0) {
      unseenMessages[user._id] = messages.length;
    }
  });
  await Promise.all(promise);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)