title: Mongoose query to pull the latest document per conversation
body: <p>I'm trying to display the most recent messages, that were sent to a user, by other users.</p>
  
  <p>So if,</p>
  
  <pre><code>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
  </code></pre>
  
  <p>If I am User B, viewing my inbox, only return Message 4 from User A to User B and Message 5 from User C to User B.</p>
  
  <p>How can I do this? I've tried this so far:</p>
  
  <pre><code>    const messages = await Conversation.find({ recipient: id })
        .sort({ date: -1 })
        .distinct("sender")
        .populate("sender")
  </code></pre>
  
  <p>But a) it doesn't populate the <code>sender</code>, it returns <code>messages [ 5d9b5142d6606f12f5434d41 ]</code> and b) I'm not sure that's the right query.</p>
  
  <p>My model:</p>
  
  <pre><code>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
    }
  });
  </code></pre>
  
  <hr>
  
  <p>Edit:</p>
  
  <p>I've tried this:</p>
  
  <pre><code>    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);
          }
        }
      )
  </code></pre>
  
  <p>An answer from <a href="https://stackoverflow.com/a/29411369/2891356">here</a>, but that returns an empty array + it doesnt seem like it would populate the <code>sender</code></p>