Hello,
I would like to get a list of my friends’ recent activities.
I have two collections I use, friends
and activities
.
I first go through all my activities from the most recent to the oldest, and then I get for each of them their list of friends.
This works, but is not optimised if there are for example a large number of activities, it will take a long time. That’s why I think that starting from friends to get their activities and then sorting them would be better, but I don’t know how to do it.
This is the schema of the friends:
exports.friendModel = model(
"friends",
new Schema({
FriendId: Number,
RequesterId: Number,
ReceiverId: Number,
Status: Number
})
);
This is the schema of the activities:
exports.activityModel = model(
"activities",
new Schema({
ActivityId: Number,
ActorId: Number,
Type: Number,
_Date: Date,
MovieId: Number,
FriendId: Number,
ContestId: Number,
LookId: Number
})
);
This is my aggregate query:
const activities = await activityModel.aggregate([
{ $sort: { _Date: -1 } },
{ $lookup: {
from: "friends",
localField: "ActorId",
foreignField: "ReceiverId",
as: "friend"
}},
{ $lookup: {
from: "friends",
localField: "ActorId",
foreignField: "RequesterId",
as: "friend"
}},
{ $match: {
$or: [
{
"friend.ReceiverId": ActorId,
"friend.Status": 1
},
{
"friend.RequesterId": ActorId,
"friend.Status": 1
}
]
}},
{ $skip: request.pageindex * 3 },
{ $limit: 3 }
]);
Can you please help me?
Thank you in advance for your reply!
Polo