猫鼬地理空间搜索:距离不起作用

时间:2016-02-07 09:37:01

标签: node.js mongodb mongoose geojson

我正在玩猫鼬和地理空间搜索,在听完教程和阅读这些内容后,我仍然无法解决问题。

我的架构:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var LocationSchema = new Schema({
    name: String,
    loc: {
        type: [Number],  // [<longitude>, <latitude>]
        index: '2dsphere'      // create the geospatial index
    }
});
module.exports = mongoose.model('Location', LocationSchema);

我的(POST)路线:

router.post('/', function(req, res) {

    var db = new locationModel();
    var response = {};

    db.name = req.body.name;
    db.loc = req.body.loc;
    db.save(function(err) {
        if (err) {
            response = {
                "error": true,
                "message": "Error adding data"
            };
        } else {
            response = {
                "error": false,
                "message": "Data added"
            };
        }
        res.json(response);
    });
 });

我的(GET)路线:

router.get('/', function(req, res, next) {
    var limit = req.query.limit || 10;

    // get the max distance or set it to 8 kilometers
    var maxDistance = req.query.distance || 8;

    // we need to convert the distance to radians
    // the raduis of Earth is approximately 6371 kilometers
    maxDistance /= 6371;

    // get coordinates [ <longitude> , <latitude> ]
    var coords = [];
    coords[0] = req.query.longitude;
    coords[1] = req.query.latitude;

    // find a location
    locationModel.find({
        loc: {
            $near: coords,
            $maxDistance: maxDistance
        }
     }).limit(limit).exec(function(err, locations) {
         if (err) {
             return res.json(500, err);
         }

         res.json(200, locations);
     });
});

我能够在数据库中存储位置,但每当我尝试搜索位置时,距离查询参数都不起作用。例如,如果我搜索距离数据库中的距离200米的地方,即使我放置了距离= 1(KM)我也没有得到结果,但如果我放置300(km)之类的东西,我会得到一些结果。距离根本不匹配。

我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

我能够通过阅读文档来解决这个问题:

index:'2dsphere'需要此查询:

$near :
      {
        $geometry: { type: "Point",  coordinates: [ <lng>, <lat> ] },
        $minDistance: <minDistance>,
        $maxDistance: <maxDistance>
      }
}

而不是这个用于遗留索引的那个:'2d':

loc: {
    $near: [<lng>, <lat>],
    $maxDistance: <maxDistance>
}

我希望这会对某人有所帮助:)。

相关问题