首页 > 解决方案 > 无法识别的管道阶段名称:'$populate'

问题描述

我正在使用以下代码来接收我的数据集,它运行良好,没有任何错误。

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

但是,就我而言,我想使用$geonear获取结果集,并且使用了以下代码。它给了我这个错误* Unrecognized pipeline stage name: '$populate'* 但是填充函数在上面的代码中运行良好。下面是给我错误的新代码。这里有什么问题?

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

标签: node.jsmongodbmongoosemongoose-populate

解决方案


您的非工作代码使用聚合管道。

填充文档没有提到任何关于聚合的内容。

看起来您试图将填充函数转换为聚合管道语法,但聚合管道由 MongoDB 服务器执行,而不由 Mongoose 解释,服务器不知道“填充”是什么,因此这不起作用。


推荐阅读