Попробуйте запрос ниже: -
const condition = {
$and: [
{ $or: [{ follower: mongoose.Types.ObjectId(userId) }, { following: mongoose.Types.ObjectId(userId) }] },
]
}
let data = await Follower.aggregate(
[
{ $match: condition },
{
$project: {
user: {
$cond: { if: { $eq: ["$follower", mongoose.Types.ObjectId(userId)] }, then: "$following", else: "$follower" }
},
_id: 1,
}
}
]
)
if(data){
const friend_id = data.map(friend => (mongoose.Types.ObjectId(friend.user)));
const index_id = data.map(friend => (mongoose.Types.ObjectId(friend._id)));
const condition = {
$and: [
{ '_id': { $nin: index_id } },
{ $or: [{ follower: { $in: friend_id } }, { following: { $in: friend_id } }] },
]
}
await Follower.aggregate(
[
{ $match: condition },
{
$project: {
user: {
$cond: { if: { $in: ["$follower", friend_id] }, then: "$following", else: "$follower" }
},
_id: 1
}
},
{
$lookup: {
from: "users",
let: { "id": "$user" },
pipeline: [
{ $match: { $expr: { $eq: ["$_id", "$$id"] } } }
],
as: "user"
}
},
{ $match: { "user._id": { $nin: friend_id } } },
{ $unwind: '$user' },
{ $group: { "_id": '$user._id', user: { $addToSet: '$user' } } },
{
$project: { _id: 1, user: { $arrayElemAt: ["$user", 0] } }
}
]
);
}