猫鼬查询可在每次会话中获取最新文档

时间:2019-10-08 06:21:37

标签: javascript node.js mongodb mongoose

我正在尝试显示其他用户发送给用户的最新消息。

那么,

User A sends Message 1 to User B,
User A sends Message 2 to User B,
User B sends Message 3 to User A,
User A sends Message 4 to User B,
User C sends Message 5 to User B

如果我是用户B,则查看我的收件箱,仅将消息4从用户A返回给用户B,将消息5从用户C返回给用户B。

我该怎么做?到目前为止,我已经尝试过:

    const messages = await Conversation.find({ recipient: id })
      .sort({ date: -1 })
      .distinct("sender")
      .populate("sender")

但是a)它没有填充sender,它返回messages [ 5d9b5142d6606f12f5434d41 ],b)我不确定这是正确的查询。

我的模特:

const conversationSchema = new Schema({
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  senderHandle: {
    type: String,
    required: true
  },
  recipient: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  text: {
    type: String,
    required: true
  },
  unread: {
    type: Boolean,
    default: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

编辑:

我已经尝试过了:

    await Conversation.aggregate(
      [
        // Matching pipeline, similar to find
        {
          $match: {
            recipient: id
          }
        },
        // Sorting pipeline
        {
          $sort: {
            date: -1
          }
        },
        // Grouping pipeline
        {
          $group: {
            _id: "$sender",
            text: {
              $first: "$text"
            },
            date: {
              $first: "$date"
            }
          }
        },
        // Project pipeline, similar to select
        {
          $project: {
            _id: 0,
            sender: "$_id"
            text: 1
          }
        }
      ],
      function(err, messages) {
        // Result is an array of documents
        if (err) {
          return res.status(400).send({
            message: getErrorMessage(err)
          });
        } else {
          console.log("latestMessages", messages);
          return res.json(messages);
        }
      }
    )

来自here的答案,但返回一个空数组+似乎不会填充sender

2 个答案:

答案 0 :(得分:1)

更改匹配管道

    $match: {
          recipient: mongoose.Types.ObjectId(id);
    }

将其添加到管道的结尾

{
    $lookup: {
       from: "users",
       localField: "sender",
       foreignField: "_id",
       as: "sender"
    }
 }

{ "$unwind": { path: "$sender" } }

答案 1 :(得分:0)

Distinct返回一个ID数组而不是对象数组,因此,它没有属性,因此无法填充它。

由于您要获取最新消息,因此建议您使用findOne而不是find。

const message = await Conversation.findOne({recipient: id}, {}, { 
                sort: { 'date' : -1 } })
                .populate('sender');
相关问题