Can't extract geo keys, longitude/latitude is

2020-08-12 18:17发布

问题:

Working with MongoDB 2dsphere to store GEOJSON and on certain stores of lat/lng I keep getting the following error:

{
  "code": 16755,
  "index": 0,
  "errmsg": "Can't extract geo keys: { _id: ObjectId('586ff135b79aa00b84181bfb'), name: \"Austin\", slug: \"Austin\", description: \"\", twitter: \"\", facebook: \"\", instagram: \"\", author: ObjectId('57b60fed8620b56af460d5c5'), tags: [], created: new Date(1483731253640), location: { address: \"Austin, TX, United States\", coordinates: [ 30.267153, -97.74306079999997 ], type: \"Point\" }, __v: 0 }  longitude/latitude is out of bounds, lng: 30.2672 lat: -97.7431",
  "op": {
    "name": "Austin",
    "slug": "Austin",
    "description": "",
    "twitter": "",
    "facebook": "",
    "instagram": "",
    "author": "57b60fed8620b56af460d5c5",
    "_id": "586ff135b79aa00b84181bfb",
    "tags": [

    ],
    "created": "2017-01-06T19:34:13.640Z",
    "location": {
      "address": "Austin, TX, United States",
      "coordinates": [
        30.267153,
        -97.74306079999997
      ],
      "type": "Point"
    },
    "__v": 0
  }
}

I can't seem to figure out why it doesn't like some lat/lng coordinates.

Here is my schema for the location field:

  location: {
    type: { type: String, default: 'Point' },
    coordinates: [Number],
    address: String
  },

and it's indexed as 2dsphere:

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

The only weird thing I can see is that the error message:

longitude/latitude is out of bounds, lng: 30.2672 lat: -97.7431",

the lat/lng are shortened from what I inputted - not sure if that has anything to do with it.

回答1:

Oh wow - I'm not sure who decided this but Mongodb expects you to store as [lng, lat], not [lat,lng] like everything else in this world.

:|



回答2:

Here is how I fixed the issue without having to swap the [lat,lng] sequence.

Somewhere in your code you are making a call to ensureIndex. Instead of calling (as I was previously doing) ...

collection.ensureIndex({ "location": "2dsphere" });

Use the following instead ...

collection.ensureIndex({ "location.coordinates":"2d"});

This completely got rid of the error at runtime and no massive refactor of data was needed.