繁体   English   中英

如何使用mongoose运行地理空间查询?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM