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
相关产品推荐
相关产品推荐

