captainavi
captainavi

Reputation: 151

Failure when searching for all polygons near a point using mongoose/mongodb

I am trying to search for any GeoJSON polygon that is with x number of kilometers from a point ordered by distance from the point. It's important that it is a GeoJSON polygon and not a GeoJSON point.

I have the following but I get an error:

'Unable to execute query: error processing query: ns=geoPolygonExample.areas limit=1000 skip=0\nTree: GEONEAR field=loc.coordinates maxdist=0.0156961 isNearSphere=1\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query'

I have checked that my index is correct and I have dropped my database in between schema changes but can't figure this out. The code I am running is below and will work on it's own.

    /* Schema */
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
var ObjectId = Schema.ObjectId;

var AreaSchema = new Schema({
  name: String,
  loc: {
    type : { type : String, default : 'Polygon' },
    coordinates: []
  }
})
AreaSchema.index({coordinates: '2dsphere'});

mongoose.model('Area', AreaSchema)
var Area = mongoose.model('Area')
/* Mongo connect */

var conn = mongoose.connect('mongodb://localhost/geoPolygonExample')
// Error handler
mongoose.connection.on('error', function (err) {
  console.log(err);
});

/* Test case */
var my_area = new Area({
  "name": "Test",
  "loc": {
    "coordinates": [[
      [ -85.56045071399187, 38.215601 ],
      [ -85.56080428954273, 38.21842155313534 ],
      [ -85.5618514284852, 38.221133713995485 ],
      [ -85.56045071399187, 38.215601 ]
    ]],
    "type" : "Polygon"
  }
});
my_area.save( function (err) {
  Area
  .find({})
  .where('loc.coordinates')
  .near({
    center: [ -85.56045071399187, 38.215601 ],
    maxDistance: 100/6371,
    spherical: true
  })
  .exec(function(err, areas){
    console.log("err: ", err);
    console.log("areas: ", areas);
  //* result: err:  { [MongoError: n/a]
  //* name: 'MongoError',
  //* message: 'n/a',
  //* '$err': 'Unable to execute query: error processing query: ns=geoPolygonExample.areas limit=1000 skip=0\nTree: GEONEAR  field=loc.coordinates maxdist=0.0156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  //* code: 17007 }
  //* areas:  undefined
  });

})

Upvotes: 0

Views: 512

Answers (1)

Brian Shamblen
Brian Shamblen

Reputation: 4703

The 2dshpere index should be created on the loc property, not the coordinates property. Try changing your index statement to:

AreaSchema.index({loc: '2dsphere'});

Also, indexes are created in the background, sometimes taking a while to be generated, depending on the amount of existing data in the collection. Since your insert and find commands are running immediately after the model is registered you may receive an error the first time you run this code, since the index will most likely not exist yet.

Upvotes: 1

Related Questions