こんにちは、開発コミュニティの皆さん! 👋
私のフルスタックエンジニアリングトラック170日目が正式に始まりました! 今日は、QuickChat のバックエンドメッセージ取得とチャット履歴処理エンドポイント(getUserforSidebar & getMessages)を Node.js、Express、MongoDB を使用して設計・実装しました! ⚙️💬
チャット取得と既読ステータスのデータベースクエリをどのように構成したかをご紹介します。
🛠️ 技術解説:メッセージ取得と未読カウンター
実装スナップショット(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.