@@ -431,14 +431,40 @@ export async function getChatRoomsCount(userId: string, page: number, size: numb
431431 {
432432 $lookup : {
433433 from : 'chat' ,
434- localField : 'roomId' ,
435- foreignField : 'roomId' ,
436- as : 'chat' ,
434+ let : { roomId : '$roomId' } ,
435+ pipeline : [
436+ {
437+ $match : {
438+ $expr : {
439+ $and : [
440+ { $eq : [ '$roomId' , '$$roomId' ] } ,
441+ { $ne : [ '$status' , Status . InversionDeleted ] } ,
442+ ] ,
443+ } ,
444+ } ,
445+ } ,
446+ {
447+ $sort : { dateTime : - 1 } ,
448+ } ,
449+ {
450+ $group : {
451+ _id : null ,
452+ chatCount : { $sum : 1 } ,
453+ lastChat : { $first : '$$ROOT' } ,
454+ } ,
455+ } ,
456+ ] ,
457+ as : 'chatInfo' ,
437458 } ,
438459 } ,
439460 {
440461 $addFields : {
441- title : '$chat.prompt' ,
462+ chatCount : {
463+ $ifNull : [ { $arrayElemAt : [ '$chatInfo.chatCount' , 0 ] } , 0 ] ,
464+ } ,
465+ lastChat : {
466+ $arrayElemAt : [ '$chatInfo.lastChat' , 0 ] ,
467+ } ,
442468 user_ObjectId : {
443469 $toObjectId : '$userId' ,
444470 } ,
@@ -450,6 +476,13 @@ export async function getChatRoomsCount(userId: string, page: number, size: numb
450476 localField : 'user_ObjectId' ,
451477 foreignField : '_id' ,
452478 as : 'user' ,
479+ pipeline : [
480+ {
481+ $project : {
482+ name : 1 ,
483+ } ,
484+ } ,
485+ ] ,
453486 } ,
454487 } ,
455488 {
@@ -458,37 +491,14 @@ export async function getChatRoomsCount(userId: string, page: number, size: numb
458491 preserveNullAndEmptyArrays : false ,
459492 } ,
460493 } ,
461- {
462- $sort : {
463- 'chat.dateTime' : - 1 ,
464- } ,
465- } ,
466- {
467- $addFields : {
468- chatCount : {
469- $size : '$chat' ,
470- } ,
471- chat : {
472- $arrayElemAt : [
473- {
474- $slice : [
475- '$chat' ,
476- - 1 ,
477- ] ,
478- } ,
479- 0 ,
480- ] ,
481- } ,
482- } ,
483- } ,
484494 {
485495 $project : {
486496 userId : 1 ,
487- title : '$chat .prompt',
497+ title : { $ifNull : [ '$lastChat .prompt', '' ] } ,
488498 username : '$user.name' ,
489499 roomId : 1 ,
490500 chatCount : 1 ,
491- dateTime : '$chat .dateTime',
501+ dateTime : { $ifNull : [ '$lastChat .dateTime', null ] } ,
492502 } ,
493503 } ,
494504 {
0 commit comments