Hello Dev Community! 👋
正式進入全端工程軌道的第 170 天!今天,我使用 Node.js、Express 和 MongoDB 為 QuickChat 設計並實作了後端的訊息取得及聊天紀錄處理端點(getUserforSidebar & getMessages)!⚙️💬
以下是聊天紀錄取得與已讀回條的資料庫查詢結構。
🛠️ 技術解析:訊息取得與未讀計數
如 messageController.js 的實作截圖所示:
1. 動態使用者發現與並行未讀計數
- 使用 Mongoose 的
$ne運算子過濾目前登入的使用者,並移除密碼欄位的投影。 - 使用
Promise.all搭配map迭代,非同步收集每位使用者卡片的未讀訊息數量:
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
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.