首页 > 解决方案 > 如何使用猫鼬运行地理空间查询?

问题描述

我无法通过猫鼬对我的 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。

标签: node.jsmongodbmongoose

解决方案


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 几何或普通坐标。检查这篇博文


推荐阅读