猫鼬我怎样才能获得每个对话的最后一条消息

时间:2021-05-14 21:22:58

标签: node.js mongodb mongoose aggregation-framework

我有以下消息架构,我想查询用户的所有对话。

我想对对话列表和消息使用相同的方案。(我试图将它们分开,但没有用。)我想要做的就是能够获取聊天列表。

最后一条消息和您正在与之通信的消息。

const messengerScheme = mongoose.Schema({ 
    users:[{
        type: mongoose.Schema.Types.ObjectId,
        ref:'User'
    }],
    from:{
        type: mongoose.Schema.Types.ObjectId, 
        ref: 'User'
    },
    message:{
        type:String,
    },
    hasImage:{
        type:Boolean,
    },
    image:{
        type:String
    }
})

假设两个用户有如下对话:

/* 1 */
{
    "_id" : ObjectId("609ee8c7593cda1de475cfff"),
    "users" : [ 
        ObjectId("60841c75b6c2a522047d1988"), 
        ObjectId("6084036ad4d4cd40a47afba4")
    ],
    "from" : ObjectId("60841c75b6c2a522047d1988"),
    "message" : "Hiiii",
    "hasImage" : false,
    "createdAt" : ISODate("2021-05-14T21:16:55.318Z"),
    "updatedAt" : ISODate("2021-05-14T21:16:55.318Z"),
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("609ee8e5593cda1de475d000"),
    "users" : [ 
        ObjectId("6084036ad4d4cd40a47afba4"), 
        ObjectId("60841c75b6c2a522047d1988")
    ],
    "from" : ObjectId("6084036ad4d4cd40a47afba4"),
    "message" : "hiiii !",
    "hasImage" : false,
    "createdAt" : ISODate("2021-05-14T21:17:25.723Z"),
    "updatedAt" : ISODate("2021-05-14T21:17:25.723Z"),
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("609ee8ec593cda1de475d001"),
    "users" : [ 
        ObjectId("6084036ad4d4cd40a47afba4"), 
        ObjectId("60841c75b6c2a522047d1988")
    ],
    "from" : ObjectId("6084036ad4d4cd40a47afba4"),
    "message" : "how are you ?",
    "hasImage" : false,
    "createdAt" : ISODate("2021-05-14T21:17:32.686Z"),
    "updatedAt" : ISODate("2021-05-14T21:17:32.686Z"),
    "__v" : 0
}

/* 4 */
{
    "_id" : ObjectId("609ee90b593cda1de475d002"),
    "users" : [ 
        ObjectId("60841c75b6c2a522047d1988"), 
        ObjectId("6084036ad4d4cd40a47afba4")
    ],
    "from" : ObjectId("60841c75b6c2a522047d1988"),
    "message" : "I am pretty fine, what about you ?",
    "hasImage" : false,
    "createdAt" : ISODate("2021-05-14T21:18:03.224Z"),
    "updatedAt" : ISODate("2021-05-14T21:18:03.224Z"),
    "__v" : 0
}

当我使用用户 ID“6084036ad4d4cd40a47afba4”进行查询时,我只想获取最后一条消息并填充用户个人资料

1 个答案:

答案 0 :(得分:0)

  • $match 用户 ID 与 users
  • $sortupdatedAt 降序排列
  • $limit 结果中有 1 条消息
db.collection.aggregate([
  { $match: { users: ObjectId("6084036ad4d4cd40a47afba4") } },
  { $sort: { updatedAt: -1 } },
  { $limit: 1 }
])

Playground


对话明智的最新单条消息:

  • $match 用户 ID 与 users
  • $sortupdatedAt 降序排列
  • $setUnion 按顺序对 users 进行排序
  • $group 按上面排序 users 并得到第一个根文档
db.collection.aggregate([
  { $match: { users: ObjectId("6084036ad4d4cd40a47afba4") } },
  { $sort: { updatedAt: -1 } },
  {
    $group: {
      _id: { $setUnion: "$users" },
      message: { $first: "$$ROOT" }
    }
  }
])

Playground