node.jsmongodbmongoosegeojsongeonear

mongodb - using $geoNear gives "geo near accepts just one argument when querying for a GeoJSON point" when using maxDistance


This appears to be a common error but I can't seem to make it work with all the suggestions I've seen. This is my setup:

// point.js (based on mongoose recommended subdocument pattern for reusing the GeoJSON definition
// see here https://mongoosejs.com/docs/geojson.html)
const mongoose = require('mongoose');

const pointSchema = new mongoose.Schema({
    type: {
        type: String,
        enum: ['Point'],
        required: true
    },
    coordinates: {
        type: [Number],
        required: true,
    }
});

exports = pointSchema;
// user.js
var schema = new Schema({
  location: {
    type: pointSchema,
  },
  ...
});

schema.index({ location: '2dsphere' });
var User = mongoose.model('User', schema);
// routeHandler.js
          const near = { type: 'Point', coordinates: [lng, lat] };
          User.aggregate([
            { $geoNear: {
              near,
              distanceField: 'dist',
              maxDistance: 100000,
              spherical: true,
            } },
            ...
          ]).exec((err, results) => {
            console.log('error or results:', err, results);
          });

And I get this error:

MongoError: Failed to determine whether query system can provide a covered projection :: caused by :: geo near accepts just one argument when querying for a GeoJSON point. Extra field found: $maxDistance: 100000.0

Most of the threads I've seen suggest that it's an issue with indexing, but you can see in user.js that I'm directly calling

schema.index({ location: '2dsphere' });

without any luck.

I'd really appreciate any suggestions, thanks!


Solution

  • I had same issue and went through many many solutions but any of them didn't work as the real issue was in data.

    In My Model had 2dsphere index which was correct but when using 2dshpere the location in the database should be in format of location : [ lng, lat ] which was the main issue. as mongodb does not validate location array this format.

    Verify both the data in DB and points specified while querying both should be correct format.

    Hope it helps someone!