Как использовать $ lookup вместо заполнения - PullRequest
0 голосов
/ 17 июня 2020

Я новичок в этом, и я обнаружил, что мне нужно использовать $ 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 } },
    { "populate": user_id },
    { "populate": "'user_id', 'img user_name _id'" }

]).then(async function(posts) {
    //some code here
});

Я хочу использовать $ lookup вместо этой функции заполнения. Пожалуйста, помогите

1 Ответ

1 голос
/ 17 июня 2020

Вот краткий набросок того, как использовать базовый синтаксис 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",
            ...
        }
    }
])
...