I'm trying to save coordinates in my 2dsphere
model.
This is my model:
var userSchema = new Schema({ email: { type: String, required: true, unique: true }, ... loc: { type: { type: "String", required: true, enum: ['Point', 'LineString', 'Polygon'], default: 'Point' }, coordinates: [Number] } }); userSchema.index({'loc': '2dsphere'}); const User = mongoose.model('User', userSchema); module.exports = User
My query to save new data is formated as follow:
email:eu@vc.com password:t12345 name:Igor type:true loc:{ coordinates: [-43.306174, -22.844279] }
And this is the error that I recieve:
{ "code": 16804, "index": 0, "errmsg": "location object expected, location array not in correct format", "op": { "email": "eu@vc.com", "password": "t12345", "name": "Igor", "_id": "5a311c016d15fc235895bef3", "created_at": "2017-12-13T12:24:33.493Z", "loc": { "coordinates": [], "type": "Point" }, "type": true, "__v": 0 } }
2 Answers
Answers 1
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()
Answers 2
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" },
Make sure that some wrong-format documents are cleared up. Keep all documents are following valid formats.
0 comments:
Post a Comment