arielcamus
arielcamus

Reputation: 773

Mongo (+Mongoose) error: Unable to find index for $geoNear query

This is my Schema:

var ActivitySchema = new Schema({
    loc: {type: [Number], index: '2dsphere'}
});

And when I try to find documents with near:

Activity.find().where('loc').near({
        center: [-71.072810, 42.370227],
        spherical: true
    }).exec(function(err, docs){
        if (err) console.log(err);
        console.log(docs);
    })

This is what I get:

{ [MongoError: Unable to execute query: error processing query: ns=bunch-test.activities limit=0 skip=0 Tree: GEONEAR field=loc maxdist=1.79769e+308 isNearSphere=1 Sort: {} Proj: {} planner returned error: unable to find index for $geoNear query] name: 'MongoError' }

I've tried defining loc in multiple ways. For example:

loc: {
        type: {
            type: String,
            enum: 'Point',
            default: 'Point'
        },
        coordinates: {
            type: [Number],
            default: [0,0],
        }
    }

And querying in multiple ways too:

Activity.find({
        loc: {
            $nearSphere: {
                $geometry: {
                    type: "Point" ,
                    coordinates: [ -71.072810, 42.370227 ]
                },
                $minDistance: 0,
                $maxDistance: 10000,
            }
        }
    })

or:

Activity.geoNear({
   type: "Point" ,
   coordinates: [ -71.072810, 42.370227 ]
},
{ maxDistance : 99999999999,
  spherical : true 
},
function(err, results, stats) {
   console.log(results);
   console.log(err);
});

But the result is always the same message:

unable to find index for $geoNear query

Any suggestion? Thanks.

Upvotes: 3

Views: 1669

Answers (1)

arielcamus
arielcamus

Reputation: 773

The problem was happening only while testing with Mocha. My after(function(done)}); was dropping the entire database at the end of every test file and the indexes where not being created again for the next test.

I solved it by replacing mongoose.connection.db.dropDatabase with Model.remove({}, callback);

Upvotes: 3

Related Questions