[英]How to run geospatial queries using mongoose?
我無法通過mongoose在Mongo集合上運行geoNear查詢。 我的架構如下所示:[1]: https : //imgur.com/kIPAHRV “schema”。 這是我的索引的截圖:[2]: https : //imgur.com/DvyHxK5 “索引”。
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的幾何形狀或普通坐標。 查看此博客文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.