Mongoose 5.0.0调用geoNear报错:geoNear is not a function
问题原因
你遇到的TypeError: Loc.geoNear is not a function是因为Mongoose 5.x已经彻底移除了Model.geoNear()这个旧的静态方法——它是Mongoose 4.x及更早版本的API,在你使用的5.0.0版本中已经不再可用了。
解决方案
针对你的需求,有两种常用的替代方案,都能实现按距离查询位置的功能:
方案1:使用聚合管道的$geoNear(推荐,功能更丰富)
这是Mongoose官方推荐的替代旧geoNear的方式,支持返回距离值、筛选条件等更多功能。修改你的控制器代码如下:
module.exports.locationsListByDistance = function(req, res) { var lng = parseFloat(req.query.lng); var lat = parseFloat(req.query.lat); var point = { type: "Point", coordinates: [lng, lat] }; // 使用聚合管道执行地理空间查询 Loc.aggregate([ { $geoNear: { near: point, // 查询的中心点 spherical: true, // 启用球面计算(对应你原来的spherical选项) maxDistance: 1000, // 最大距离,单位为米(和你原来的设置一致) distanceField: "distance", // 结果中新增一个字段存储计算出的距离 includeLocs: "coords" // 可选:返回位置坐标(方便验证) } } ]) .exec(function(err, results) { if (err) { return res.status(500).json({ error: err.message }); } console.log('查询结果:', results); res.status(200).json(results); }); };
方案2:使用find配合$nearSphere(更简洁,适合基础查询)
如果你只需要获取附近的位置文档,不需要返回距离值,这种方式更简单:
module.exports.locationsListByDistance = function(req, res) { var lng = parseFloat(req.query.lng); var lat = parseFloat(req.query.lat); var point = { type: "Point", coordinates: [lng, lat] }; Loc.find({ coords: { $nearSphere: point, // 球面附近查询 $maxDistance: 1000 // 最大距离,单位米 } }) .exec(function(err, locations) { if (err) { return res.status(500).json({ error: err.message }); } console.log('查询结果:', locations); res.status(200).json(locations); }); };
额外注意事项
你的模型中coords字段的定义是正确的:
coords: { type: [Number], index: '2dsphere' }
2dsphere索引是支持球面地理空间查询的必要条件,确保你已经为这个集合创建了该索引(Mongoose会在模型初始化时自动创建,但如果之前有旧数据,可能需要手动重建索引)。
内容的提问来源于stack exchange,提问作者Sid B
相关产品推荐
相关产品推荐

