Suthura Sudharaka
Suthura Sudharaka

Reputation: 673

How to use $lookup instead of populate

I'm very new to this and I have found that I have to use the $lookup instead of populate in my code. Since I have no experience with this I need some help with how to do it to the below code.

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
});

I want to use $lookup instead of this populate function. Please help

Upvotes: 0

Views: 94

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

Here's a quick sketch of how to use the basic $lookup syntax. I had to speculate some field names as you didn't include a schema for all collections but it should be fairly straight forward to fix in case they are wrong.

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",
            ...
        }
    }
])

Upvotes: 1

Related Questions