你好,开发者社区!👋
今天是我全栈工程学习轨道的第 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);
进入全屏模式 退出全屏模式
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.