【发布时间】:2020-03-29 20:57:10
【问题描述】:
这是我的架构:
const userSchema = mongoose.Schema({
coordinates: {
type: { type: String },
coordinates: [],
},
})
然后我添加这个:
userSchema.index({ coordinates: "2dsphere" });
我想找到一个半径内的所有坐标。这是我正在调用的方法:
router.post('/users/query', async(req,res)=>{
var pageOptions = {
page: req.body.page || 0,
limit: 10
}
const query ={ location: {
$near: {
$maxDistance: req.body.searchQuery.maxDistance,
$geometry: {
type: "Point",
coordinates: req.body.searchQuery.coordinates
}
}
}}
console.log(query)
User.find(query)
.skip(pageOptions.page*pageOptions.limit)
.limit(pageOptions.limit)
.exec(function (error, users) {
if(error) { res.status(500).json({error}); return; };
User.countDocuments(query).exec((error,total)=>{
if(error) {
res.status(500).json({error})
}else{
res.status(200).json({users,total});
};
})
})
})
我在这篇文章中这样做了:https://medium.com/@galford151/mongoose-geospatial-queries-with-near-59800b79c0f6
但我得到错误 $geoNear, $near, and $nearSphere are not allowed in this context。有人知道为什么吗?
这是我的搜索查询:
{ searchQuery:
{ coordinates: [ 9.993681899999956, 53.5510846 ],
maxDistance: 1000 } }
【问题讨论】:
标签: javascript node.js mongodb express mongoose