My goal is to retrieve all messages exchanged between User A and any other user.
This is my schema structure:
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"
},
date: {
type: Date,
default: Date.now
}
});
Here is the query I have been using:
await MostRecentMessages.aggregate(
[
{
$match: {
$or: [
{
to: id
},
{
from: id
}
]
}
},
{ $sort: { date: -1 } },
{
$group: {
_id: "$from",
from: {
$first: "$from"
},
to: {
$first: "$to"
},
conversation: {
$first: "$conversation"
},
date: {
$first: "$date"
}
}
},
{
$lookup: {
from: "conversations",
localField: "conversation",
foreignField: "_id",
as: "conversation"
}
},
{ $unwind: { path: "$conversation" } },
{
$project: {
from: {
$cond: { if: { $eq: ["$to", id] }, then: "$from", else: "$to" }
},
to: {
$cond: { if: { $eq: ["$to", id] }, then: "$to", else: "$from" }
},
conversation: "$conversation"
}
}
],
function(err, docs) {
if (err) console.log(err);
else console.log("docs", docs);
return res.json(docs);
}
);
Despite following this structure, the query continues to return an empty array. What could be causing this issue? Additionally, I am aiming to populate the conversation
field by utilizing the $lookup
, but it seems like there might be a fundamental flaw in my approach since no documents are being found.