Save location in mongodb

I am trying to save the coordinates in my model 2dsphere.

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 request to save new data is formed as follows:

email:eu@vc.com
password:t12345
name:Igor
type:true
loc:{
coordinates: [-43.306174, -22.844279]
}

And this is the error I get:

{
    "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
    }
}
+4
source share
2 answers

You can have both the 2d index and 2dsphere in the collection.

The error below indicates that you have a 2d index.

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

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

The error ( first part and second part ) below indicates that you have an index with 2 spheres.

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

, {"loc": {"coordinates": [23, 25] }}, 2d .

. db.users.getIndexes()

2d ( ). 2- (, {"loc":[23, 25]}) .

db.users.dropIndex( "loc_2d" ) 

, 2d- .

, .

db.users.drop()
+4
  • loc geoJSON. , loc, .

    "loc": {  
        "coordinates": [],  //should NOT be an empty array, should be with 2 number items such as [ -43.306174, -22.844279]
        "type": "Point"  
    },  
    
  • , . .

+1

Source: https://habr.com/ru/post/1690708/


All Articles