Save location in mongodb Save location in mongodb mongoose mongoose

Save location in mongodb


You may have both 2d and 2dsphere index on collection.

The error below indicates you have a 2d index.

"errmsg": "location object expected, location array not in correct format",

So when you try to save spherical coordinates ({"loc": {"coordinates": [23, 25],"type": "Point"}) you get the error when mongodb builds the index.

The error (first part & second part) below indicates you have a 2d sphere index.

"errmsg": "Can't extract geo keys: {...loc: { coordinates: [23, 25] }} unknown GeoJSON type

So when you change to {"loc": {"coordinates": [23, 25] }}, 2d sphere index fails to build.

You can verify the indexes. db.users.getIndexes()

Drop the 2d index (still there for backward compatibility). 2d sphere index supports both legacy coordinates (eg {"loc":[23, 25]}) and geo coordinates.

db.users.dropIndex( "loc_2d" ) 

This should work when 2d sphere index rebuilds index for collection.

Drop the collection and start over if above solution doesn't work.

db.users.drop()


  1. All your documents' loc property must follow geoJSON format. I see some documents are with a empty array of coordinates in loc property which is wrong.

    "loc": {      "coordinates": [],  //should NOT be an empty array, should be with 2 number items such as [ -43.306174, -22.844279]    "type": "Point"  },  
  2. Make sure that some wrong-format documents are cleared up. Keep all documents are following valid formats.