我正在使用 express 和 mongoose 构建一个 api。我有一个 Reviews 集合,它有一个存储 geoJSON 的位置字段。我正在尝试使用 aggregate 和 $geoNear 查询我的评论集合。
这是我的 ReviewSchema 中的相关部分:
location: {
type: {
type: String,
default: 'Point'
},
coordinates: {
type: [Number]
}
}
我还添加了一个 2dsphere 索引:
ReviewSchema.index({ location: '2dsphere' });
我能够使用 find 和 $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))
});
我的查询语法基于 $geoNear 的 mongoDB 文档。我对 Mongoose 的使用不正确吗?非常感谢任何帮助!
最佳答案
问题在于坐标始终应该是数字,而您将其作为 String
所以改为将它们转换为整数或浮点值
Review.aggregate([{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [parseFloat(req.params.longitude), parseFloat(req.params.latitude)]
},
"spherical": true,
"maxDistance": 10 * 1609,
"distanceField": "distance"
}
}])
关于node.js - 近场必须是点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507357/