我正在尝试将MongoDB GeoSpatial query转换为猫鼬,但是我没有任何运气。 MongoDB查询如下所示:

var neighborhood = db.neighborhoods.findOne( { geometry: { $geoIntersects: { $geometry: { type: "Point", coordinates: [ -73.93414657, 40.82302903 ] } } } } )

然后将附近的值插入餐厅的$geometry查询中。

db.restaurants.find( { location: { $geoWithin: { $geometry: neighborhood.geometry } } } )

然后,您将获得附近的所有餐馆。

因此,我想出的是以下使用Mongoose和Express的方法,这显然是错误的,而这只是我对MongoDB查询的翻译。

exports.getRestaurantInNeighborhood = function(req, res, next) {

  var geojsonPoint = {type: 'Point', coordinates: [-73.93414657, 40.82302903]};
  var neighborhood = Neighborhood.findOne({geometry: {$geoIntersects: {$geometry: geojsonPoint}}})

  Restaurant.find({location: { $geoWithin: { $geometry: neighborhood.geometry } } } )
  .then(function(data) {
    res.json(data);
  }, function(err) {
    next(err);
  });
}


我相信这是行不通的,因为在neighborhood返回数据时我还没有得到Restaurant的值,这给了我geometry中没有neighborhood对象的错误。因此,neighborhood没有任何返回。

感谢您对解决此问题的任何帮助。

更新:

我想到的是可行的,如下所示:

exports.getRestaurantInNeighborhood = function(req, res, next) {

  var geojsonPoint = {type: 'Point', coordinates: [-73.93414657, 40.82302903]};
  Neighborhood.findOne({geometry: {$geoIntersects: {$geometry: geojsonPoint}}}, function(err, data) {
  }).then(function(data) {
    Restaurant.find({location: { $geoWithin: { $geometry: data.geometry } } })
    .then(function(data) {
      res.json(data);
    }, function(err) {
      next(err);
    });
  });
}


但是,我不确定这是否最佳。

最佳答案

为了扩展您的更新,无需为每个promise指定拒绝处理程序,并且您不应该这样做。只需正确地兑现您的承诺,并在最后处理错误即可。任何错误都将通过整个链传播到catch()块。

exports.getRestaurantInNeighborhood = function (req, res, next) {

    var geojsonPoint = {
        type: 'Point',
        coordinates: [-73.93414657, 40.82302903]
    };

    return Neighborhood
        .findOne({
            geometry: {
                $geoIntersects: {
                    $geometry: geojsonPoint
                }
            }
        })
        .then(function (data) {
            // Make sure there is a return.
            return Restaurant.find({
                location: {
                    $geoWithin: {
                        $geometry: data.geometry
                    }
                }
            });
        })
        .then(function (data) {
            // This gets called if there are no errors.
            res.json(data);
        })
        .catch(function (err) {
            // Here you handle errors. or you can call next(err) and
            // handle it in a middleware.
            console.warn(err);
        });
}

10-06 04:00