'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 1:[1]

I also faced the same error and after researching a lot I found that which running the aggregation query. I was passing the coordinates as array of string which should be an array of Number.

{
        $geoNear: {
          near: {
            type: "Point",
            coordinates: [103.83797, 1.46103],
          },
          distanceField: "dist.calculated",
          maxDistance: distance,
          includeLocs: "dist.location",
          spherical: true,
        },
      },

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adhikansh Mittal