简体   繁体   中英

Mongoose geospatial search: distance not working

I was playing around with mongoose and geospatial search and after following tutorials and reading stuff on here, I still couldn't ge my head around the problem.

My schema:

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);

My (POST) route:

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);
    });
 });

My (GET) route:

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);
     });
});

I am able to store locations in the database but whenever i try to search for a location, the distance query param doesn't work. If for example I search for a place that is 200m away from the one in the database, even if I put ?distance=1 (KM) I don't get results, but if I put something like 300 (km) I get some results. Distance doesn't match at all.

What am I doing wrong?

Thanks

I was able to fix it this way reading the docs:

index: '2dsphere' requires this query:

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

and not this one which is meant to be used for the legacy index: '2d':

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

I hope this will help someone :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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