You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS应用使用$geoNear聚合操作报错,提示存在额外字段$maxDistance

问题解决:$geoNear聚合阶段报错处理

错误原因

当$geoNear的near参数使用GeoJSON格式的点时,必须将GeoJSON对象包裹在$geometry字段中,不能直接传入。如果直接传递GeoJSON对象,MongoDB会将其识别为旧版坐标参数,进而限制仅允许单个参数,导致maxDistance等字段被判定为多余参数抛出错误。

修正后的代码

Ninja.aggregate([
    {
        $geoNear: {
            near: {
                $geometry: {
                    type: "Point",
                    coordinates: [parseFloat(req.query.lng), parseFloat(req.query.lat)]
                }
            },
            distanceField: "dist.calculated",
            spherical: true,
            maxDistance: 100000
        }
    }
])
.then(function (ninja) {
    res.send(ninja);
}).catch(next);

额外注意事项

  • 确保你的Ninja集合已经创建了2dsphere索引,否则$geoNear无法正常执行。假设模型中存储地理位置的字段名为location,创建索引的代码如下:
Ninja.createIndex({ location: "2dsphere" });
  • 当spherical: true且使用GeoJSON时,maxDistance的单位是米,当前设置的100000代表搜索半径100公里,可根据需求调整数值。

内容的提问来源于stack exchange,提问作者Lilia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:47:33