【问题标题】:How to run geospatial queries using mongoose?如何使用猫鼬运行地理空间查询?
【发布时间】:2019-10-24 18:33:20
【问题描述】:

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

【问题讨论】:

  • 首先,您在ifelse 分支中都返回500 响应,基本上总是如此。其次var response 是一个承诺。您需要提供回调来处理查询结果,或者等待 promise 被解决或拒绝。

标签: node.js mongodb mongoose


【解决方案1】:

Mongoose 有一些很好的便利函数可以在集合上运行地理查询。
来自docs 的示例:

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 几何或普通坐标。 查看此博客post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 2012-05-14
    • 1970-01-01
    • 2014-07-14
    • 2017-06-04
    • 2014-09-17
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多