[英]Mongoose query to pull the latest document per conversation
我正在嘗試顯示其他用戶發送給用戶的最新消息。
因此,如果,
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,查看我的收件箱,只返回用戶 A 的消息 4 給用戶 B 和用戶 C 的消息 5 給用戶 B。
我怎樣才能做到這一點? 到目前為止,我已經嘗試過:
const messages = await Conversation.find({ recipient: id })
.sort({ date: -1 })
.distinct("sender")
.populate("sender")
但是a)它沒有填充sender
,它返回messages [ 5d9b5142d6606f12f5434d41 ]
和b)我不確定這是正確的查詢。
我的 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
}
});
編輯:
我試過這個:
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
更改匹配管道
$match: {
recipient: mongoose.Types.ObjectId(id);
}
在管道末尾添加這些
{
$lookup: {
from: "users",
localField: "sender",
foreignField: "_id",
as: "sender"
}
}
{ "$unwind": { path: "$sender" } }
Distinct 返回一個 id 數組而不是對象數組,因此,它沒有屬性,您無法填充它。
由於您想獲取最新消息,因此我建議您使用 findOne 而不是 find。
const message = await Conversation.findOne({recipient: id}, {}, {
sort: { 'date' : -1 } })
.populate('sender');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.