Search code examples
node.jsmongodbmongoosemongoose-populate

Unrecognized pipeline stage name: '$populate'


I was using the following code to receive my data set and it worked fine without any error.

const postslist = await postSchemaModel.find()
        .limit(limit)
        .skip(startIndex)
        .sort({ createdAt: -1 })
        .populate(user_id)
        .populate("user_id", "img user_name _id");

But , In my case I want to get the result set with $geonear and I used the following code. There it gives me this error * Unrecognized pipeline stage name: '$populate'* But the populate function was working fine with the above code. Below one is the new code that gives me the error. What can be the fault here ?

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

Solution

  • Your non-working code uses an aggregation pipeline.

    populate documentation does not mention anything about aggregation.

    It looks like you attempted to translate the populate function into aggregation pipeline syntax, but the aggregation pipeline is executed by MongoDB server and not interpreted by Mongoose and the server has no idea what "populate" is, hence that just doesn't work.