【问题标题】:How to get the last message of the user's conversations and group it in a list in mongodb如何获取用户对话的最后一条消息并将其分组到mongodb的列表中
【发布时间】:2021-10-06 05:21:44
【问题描述】:

我想获取一个用户和另一个用户之间的最后一条消息,该消息在一个名为聊天的集合中,所有成员之间都有对话,但我想过滤以便只有一个用户和另一个用户之间的最后一条消息出现。有什么方法可以在 mongodb 中得到这个?

例如,我想获取用户 Carlos 发送/接收的最后一条消息。我想要一个这样的列表

例子:

Chat between John Doe and me
John Doe: Hi

Chat between Max and me
Max: Hello

Chat between Jessica and me
Owner: Hello Jessica

型号

1. owner = ObjectId
2. recipient = ObjectId
3. content = Message content
4. createdAt / updatedAt = Autogenerate

我目前正在尝试这个,但错误是我收到了用户收到的最后一条消息,以及用户发送给该用户的最后一条消息

我正在尝试的代码

const chatData = await this.chatModel
  .find({ $or: [{ owner: userId }, { recipient: userId }] })
  .populate('owner', DEFAULT_POPULATE_SELECT_USER)
  .populate('recipient', DEFAULT_POPULATE_SELECT_USER)
  .sort({ createdAt: 'desc' })
  .select({ __v: false })
  .lean();

const chatLog: ChatModel[] = chatData.reduce((unique, item: any) => {
  if (!item.recipient) return unique;
  return unique.some((x) => x.recipient._id == item.recipient._id) ? unique : [...unique, item];
}, []);

【问题讨论】:

    标签: javascript mongodb mongoose mongodb-query


    【解决方案1】:

    试试这个查询

    示例用户架构

    {
        _id: ObjectId,
        name: String,
        createdAt: Date,
        updatedAt: Date
    }
    

    聊天架构示例

    {
        owner: ObjectId,
        recipient: ObjectId,
        content: String
        createdAt: Date,
        updatedAt: Date
    }
    

    查询

    const userId = ObjectId('xxxx...')
    await chatModel.aggregate([
        { $match: { $or: [ { owner: userId }, { recipient: userId }] } },
        { $addFields: {
            me: { $cond: [ { $ne: [ '$owner', userId ] }, '$recipient', '$owner' ] },
            other: { $cond: [ { $ne: [ '$owner', userId ] }, '$owner', '$recipient' ] },
        } },
        { $group: { _id: { me: '$me', other: '$other' }, document: { $last: '$$ROOT' } } },
        { $replaceRoot: { newRoot: '$document' } },
        { $lookup: { from: 'users', let: { owner: '$owner' }, as: 'ownerInfo', pipeline: [ { $match: { $expr: { $and: [ { $eq: [ '$_id', '$$owner' ] } ] } } } ] } },
        { $unwind: '$ownerInfo' },
        { $lookup: { from: 'users', let: { recipient: '$recipient' }, as: 'recipientInfo', pipeline: [ { $match: { $expr: { $and: [ { $eq: [ '$_id', '$$recipient' ] } ] } } } ] } },
        { $unwind: '$recipientInfo' },
        { $sort: { createdAt: -1 } }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多