简体   繁体   中英

Mongoose query to pull the latest document per conversation

I'm trying to display the most recent messages, that were sent to a user, by other users.

So if,

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

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.

How can I do this? I've tried this so far:

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

But a) it doesn't populate the sender , it returns messages [ 5d9b5142d6606f12f5434d41 ] and b) I'm not sure that's the right query.

My model:

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
  }
});

Edit:

I've tried this:

    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);
        }
      }
    )

An answer from here , but that returns an empty array + it doesnt seem like it would populate the sender

Change your match pipeline

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

Add these at the end of pipeline

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

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

Distinct returns an array of ids not array of objects, therefore, it has no properties and you cannot populate it.

Since you want to get the latest message, I recommend you use findOne instead of find.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM