node.js - 如何使用猫鼬运行地理空间查询?
问题描述
我无法通过猫鼬对我的 Mongo 集合运行 geoNear 查询。我的架构如下所示:[1]:https ://imgur.com/kIPAHRV “架构”。这是我的索引的屏幕截图:[2]:https ://imgur.com/DvyHxK5 "indexes"。
var url = 'mongodb://*******';
MongoClient.connect(url, function(err, db) {
if(err) {
res.sendStatus(500)
} else {
if(db.places) {
console.log("Connected successfully to server");
var response = db.places.find({ coordinates : { $near : { $geometry : {
type : "Point" ,
coordinates : [req.query.lomg, req.query.lat] },
$maxDistance : 10000 /* 10 kms */
}
}
})
res.send(response)
}
res.sendStatus(500);
}
});
代码出错并总是转到 else 块,从而返回 500。
解决方案
Mongoose有一些很好的便利功能可以在集合上运行地理查询。文档
中的一个示例:
const denver = { type: 'Point', coordinates: [-104.9903, 39.7392] };
return City.create({ name: 'Denver', location: denver }).
then(() => City.findOne().where('location').within(colorado)).
then(doc => assert.equal(doc.name, 'Denver'));
所以在你的情况下,它会变成这样:
db.find().where('coordinates').within({
type : "Point" ,
coordinates : [req.query.lomg, req.query.lat]});
如果要直接使用 MongoDb 语法,可以使用$aggregate
运算符,如下所示:
var response =
db.aggregate([{
$geoNear: {
includeLocs: "coordinates",
distanceField: 'distance',
near: {type: 'Point', coordinates: [[req.query.lomg, req.query.lat]},
maxDistance: 10000,
spherical: true
}
}]);
请注意,该includeLocs
字段接受 GeoJson 几何或普通坐标。检查这篇博文。
推荐阅读
- c++ - 以当前(LocalSystem)用户的默认权限运行进程
- r - 通过 R 从 Bloomberg 检索存储为文本 (YES/NO) 的数据
- date - 根据日期和年份识别当前周
- javascript - 第二条线图,图表js需要不同的标签
- animation - FFMPEG 由于色彩空间不匹配而丢帧
- azure - 如何通过 Ansible 将 Azure Application Insights 部署到生产环境
- rest - 完全保护 REST API
- php - 如何动态设置背景图像大小?
- reactjs - 如何使用 Sheet.Best API 从我的 GatsbyJS 网站将数据发布到 Google 表格?
- arrays - Array Redim Preserve 将列转置为多行错误下标超出范围错误