Search code examples
mongoosegeolocation

Mongoose unable to find index for $geoNear query


I got this error when trying to query a model based on location.


Solution

  • After combining some answers on SO, here's the full implementaion.

    Model

    // model.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var ModelSchema = new Schema({
      location: {
        type: [Number],
        index: '2dsphere'
      }
    });
    
    ModelSchema.index({ location: 1});
    
    module.exports = mongoose.model('model', ModelSchema);
    

    Controller

    // controller.js
    Model = require('path/to/model')
    exports.getByLocation = function(req, res, next) {
      var coords = [+req.query.lon, +req.query.lat];
    
      Model.where('location').near({
          center: {
              type: 'Point',
              coordinates: coords
          }
        })
        .then(function(docs) {
          res.json(docs);
        })
        .catch(next);
    }
    

    Hope this helps :)