Search code examples
node.jsmongodbmongoosemongodb-querygeojson

Near operator for geojson point returning error when maxdistance is used in query


I am trying to store some geojson points in mongo db.Here is the mongoose schema I have defined.

new mongoose.Schema({
        itemName:String,
        loc:{ type: [Number], index: '2dsphere'}
    });

Next I am trying to run a near operator to find out some points nearby.This is how I have defined the near query.

Model.where('loc').near({ center: { type:"Point",coordinates: [10,10] }, maxDistance: 20 }).exec(function(err,data){
            console.log(err);
            if (!err && data) {
                console.log("Success");
            } else {
                console.log("Error");
            }
        });

But this is returning an error value as follows:

{ [MongoError: Can't canonicalize query: BadValue geo near accepts just one argu ment when querying for a GeoJSON point. Extra field found: $maxDistance: 20] name : 'MongoError' }

If i remove the maxDistance it is returning all the collection elements.

Any idea why this error is coming?Thanks in advance for any help


Solution

  • Mongoose is still using the 'geoNear' database command form. This is considered obsolete in all ongoing versions of MongoDB.

    Use the standard query form instead, which has been integrated with the standard query engine since MongoDB 2.6 and greater versions:

    Model.find({
        "loc": { 
            "$near": {
                "$geometery": {
                    "type": "Point",
                    "coordinates": [ 10,10 ],
                },
                "$maxDistance": 20
            }
        }
    },function(err,docs) {
    
        // do something here
    });
    

    It's JavaScript, a "dynamically typed language". You don't need these ridiculous function helpers that are needed for strict typed languages with no dynamic constructs for defining and Object structure.

    So do what the manual (which all examples are in JSON notation, which JavaScript natively understands) tells you to do and you are always fine.