Wednesday, 15 March 2017

Including records with empty location field in mongoose near query

I have been trying to create a mongoose model in which I can have a geojson location field and query on the records based on location, but I also want the records with the location field not set to be included automatically.

I have even set the sparse condition true to make sure I can create empty location fields but calling $near query produces this error:

unable to find index for $geoNear query

I have trying to find an answer for how this query should be designed, any help is appreciated.

This is my model:

var EventSchema = new mongoose.Schema({
  loc: {
    "type": { type: String, default: 'Point' },
    coordinates: [Number]
  },
  pos: Number,
  active: Boolean
});
EventSchema.index({ loc: '2dsphere' }, { sparse: true });

And this is the query:

exports.index = function (req, res, next) {
    Event
      .find({ active: true })
      .near('loc', { center: point, spherical: true, maxDistance: 5000,   distanceMultiplier: 6378.1 })
      .sort('pos')
      .limit(6)
      .lean(true)
      .exec(function (err, events) {
      if(!events) {
        res.status(400).json(err || {status: false, message: 'No Events'});
      }
      else
        res.status(200).json(events);
    });
}



via Parichit

No comments:

Post a Comment