我建设使用的快递和猫鼬的API。我有一个评论的集合,具有存储GeoJSON的位置字段。我试图用骨料和$ geoNear查询我的收藏评论。
下面是从我ReviewSchema相关部分:
location: {
type: {
type: String,
default: 'Point'
},
coordinates: {
type: [Number]
}
}
我还添加了2dsphere指数:
ReviewSchema.index({ location: '2dsphere' });
我能够成功地查询使用查找和$ nearSphere集合:
router.get('/:longitude/:latitude/:dist', (req, res) => {
Review.find({
location: {
$nearSphere: {
$geometry: {
type: 'Point',
coordinates: [req.params.longitude, req.params.latitude]
},
$maxDistance: req.params.dist * 1609.34
}
}
})
.then(reviews => res.json(reviews))
});
当试图汇总使用和$ geoNear但是我得到一个错误: “近场必须点” 下面是与查询路径:
router.get('/:longitude/:latitude', (req, res) => {
Review.aggregate([{
$geoNear: {
near: {
type: "Point",
coordinates: [req.params.longitude, req.params.latitude]
},
spherical: true,
maxDistance: 10 * 1609,
distanceField: 'distance'
}
}])
.then(reviews => res.json(reviews))
.catch(err => console.log(err))
});
我的查询语法基于关闭MongoDB的文档$ geoNear。我是不是正确使用这个与猫鼬?任何帮助非常感谢!
问题是你,而把它作为String
它总是坐标应该是数字
因此,而不是将它们转换为整数或浮点数值
Review.aggregate([{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [parseFloat(req.params.longitude), parseFloat(req.params.latitude)]
},
"spherical": true,
"maxDistance": 10 * 1609,
"distanceField": "distance"
}
}])