Вот краткий набросок того, как использовать базовый синтаксис c $lookup
. Мне пришлось предположить некоторые имена полей, так как вы не включили схему для всех коллекций, но это должно быть довольно просто исправить, если они ошибаются.
postSchemaModel.aggregate([
{
"$geoNear": {
"near": {"type": "Point", "coordinates": [6.7336665, 79.8994071], "Typology": "post"},
"distanceField": "dist.calculated",
"maxDistance": 5000,
"includeLocs": "dist.location",
"spherical": true
}
},
{"limit": limit},
{"skip": startIndex},
{"$sort": {"createdAt": -1}},
{
$lookup: {
from: "users", //user collection name,
localField: "user", // this is the field in the post document that links to user
foreignField: "_id", // this is the field in the user document that links to localField specified above.
as: "users" // name of new field
}
},
// users is now an array of matched users (could be an empty array if no user was matched), assuming a post can only have 1 user we should unwind this
{
$unwind: {
path:"$users"
preserveNullAndEmptyArrays: true // true if you want to keep posts with no matched user.
}
},
{
//now you can $project whichever structure you want
$project: {
user_id: "$users._id",
...
}
}
])