我正在尝试使用Mongo的GeoSpatial功能根据坐标定位文档。 我需要创建索引才能使其正常工作-但似乎无法创建索引?你能帮忙吗?
我将介绍到目前为止的内容。
DirectorySearcher
这是将其放入数据库的路由。我尝试在这里创建索引。
Get-ADUser
})
索引在我的终端中引发错误,但是无论如何都会创建位置。它在数据库中。
//User saves the location using a PUT Command.
props.updateBandLocation({
geometry: {
type: "Point",
coordinates: [ lat, lon ]
}
})
最后,我正在尝试使用此路线将所有文档移到某个点附近。
router.put('/:id', (req, res) => {
quoteGenerator.findByIdAndUpdate({_id: req.params.id}, req.body).then(() => {
quoteGenerator.findOne({_id: req.params.id}).then(generator => res.send(generator))
quoteGenerator.createIndex( { bandLocation: "2dsphere" } )
})
});
感谢您提供的任何帮助!
这是我的架构-
//How the query looks in the database
"bandLocation": {
"geometry": {
"type": "Point",
"coordinates": [
32.96179,
-96.82916850000001
]
}
},
答案 0 :(得分:0)
好吧,据我所知,我们有两个问题:
从2dsphere索引docs:
2dsphere索引支持存储为GeoJSON对象和旧式坐标对的数据
GeoJSON对象是什么类型?它们是{ type: <GeoJSON type> , coordinates: <coordinates> }
legacy coordinates pairs是什么类型?它们的形式为:[<longitude>, <latitude> ]
或{ <field1>: <x>, <field2>: <y> }
所以我们可以看到bandLocation
都不是,您需要使用
quoteGenerator.createIndex( { "bandLocation.geometry": "2dsphere" } )
您的坐标顺序错误,您需要按经度然后按纬度的顺序指定。以度为单位的有效纬度范围是-90和+90。您的-96纬度值超出范围。
因此,将您的文档更改为[-96.82916850000001, 32.96179]
。
现在我们只需要调整您的查询:
quoteGenerator.find({
"bandLocation.geometry":
{ $near: {
$geometry: {
type : "Point",
coordinates : [-req.params.lng, +req.params.lat],
}
}
}
})
**弹出的另一件事是,实际上每次有一个函数调用时,您都要创建(尝试创建)索引,实际上您应该只创建一次。它不应该是您代码的一部分。现在这不会引发错误,但是由于Mongo在更改/插入时自动建立索引文件而变得多余了。