Я пытаюсь отобразить список последних сообщений между пользователем А и любым другим пользователем. Вот что у меня есть, но позвольте мне объяснить, что не так с приведенным ниже запросом:
Если пользователь A отправляет сообщение «Test1» пользователю B, а пользователь B отвечает «Test2», а затем пользователь A отвечаетс 'Test3', тогда будет отображаться только сообщение Test2.
Сначала появится сообщение 'Test1', так как это первое сообщение в диалоге, но с этого момента оно будет отображать только пользователя B. messages.
В данном случае я хочу, чтобы запрос всегда возвращал «Test3». Вот что у меня есть:
Моя модель:
const MostRecentMessageSchema = new Schema({
to: {
type: mongoose.Schema.Types.ObjectId,
ref: "user"
},
from: {
type: mongoose.Schema.Types.ObjectId,
ref: "user"
},
conversation: {
type: mongoose.Schema.Types.ObjectId,
ref: "conversation"
},
deletedBy: {
type: [String]
},
date: {
type: Date,
default: Date.now
}
});
await MostRecentMessages.aggregate(
[
{
$match: {
$or: [
{ from: mongoose.Types.ObjectId(userId) },
{ to: mongoose.Types.ObjectId(userId) }
],
deletedBy: { $ne: mongoose.Types.ObjectId(userId) },
_id: { $ne: filteredIds }
}
},
{ $project: { _id: 1, from: 1, to: 1, conversation: 1, date: 1 } },
{ $sort: { date: -1 } },
{
$group: {
_id: {
userConcerned: {
$cond: {
if: {
$eq: ["$to", mongoose.Types.ObjectId(userId)]
},
then: "$to",
else: "$from"
}
},
interlocutor: {
$cond: {
if: {
$eq: ["$to", mongoose.Types.ObjectId(userId)]
},
then: "$from",
else: "$to"
}
}
},
from: { $first: "$from" },
to: { $first: "$to" },
date: { $first: "$date" },
conversation: { $first: "$conversation" }
}
},
{
$lookup: {
from: "conversations",
localField: "conversation",
foreignField: "_id",
as: "conversation"
}
},
{ $unwind: { path: "$conversation" } },
{
$lookup: {
from: "users",
localField: "to",
foreignField: "_id",
as: "to"
}
},
{ $unwind: { path: "$to" } },
{
$lookup: {
from: "users",
localField: "from",
foreignField: "_id",
as: "from"
}
},
{ $unwind: { path: "$from" } }
],
function(err, mostRecentMessages) {
if (err) {
console.log("Error fetching most recent messages", err);
} else {
if (connectedUsersAllMessages[userId]) {
allMessagesSocket.sockets.connected[
connectedUsersAllMessages[userId].socketId
].emit("response", {
mostRecentMessages
});
}
}
}
);
}, 5000);
}
Что я здесь не так делаю? Вот это POC . Он должен вернуть
{
from: "A",
to: "C",
number: 3,
message: "A-C Test 4"
},
, но возвращает,
{
from: "C",
to: "A",
number: 3,
message: "A-C Test 3"
},