【问题标题】:Save location in mongodb在mongodb中保存位置
【发布时间】:2018-05-27 11:28:29
【问题描述】:

我正在尝试将坐标保存在我的 2dsphere 模型中。

这是我的模型:

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

我保存新数据的查询格式如下:

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

这是我收到的错误:

{
    "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
    }
}

【问题讨论】:

  • 也许这会有所帮助:stackoverflow.com/questions/27218389/…
  • @maxpaj @Neodan 尝试在帖子中运行此错误的方式:"errmsg": "Can't extract geo keys: { _id: ObjectId('5a31c82b3a84041e1c42ee78'), email: \"eu@vc.com\", password: \"tbi729\", name: \"Igor\", created_at: new Date(1513211947354), loc: { coordinates: [] }, type: true, __v: 0 } unknown GeoJSON type: { coordinates: [] }",

标签: node.js mongodb mongoose geospatial


【解决方案1】:
  1. 您所有文档的 loc 属性必须遵循 geoJSON 格式。我看到一些文档在 loc 属性中有一个空的 coordinates 数组,这是错误的。

    "loc": {  
        "coordinates": [],  //should NOT be an empty array, should be with 2 number items such as [ -43.306174, -22.844279]
        "type": "Point"  
    },  
    
  2. 确保清除了一些格式错误的文档。保持所有文件遵循有效格式。

【讨论】:

    【解决方案2】:

    您可能同时拥有 2d 和 2dsphere 索引。

    下面的error 表示您有一个二维索引。

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

    因此,当您尝试保存球坐标 ({"loc": {"coordinates": [23, 25],"type": "Point"}) 时,您会在 mongodb 构建索引时遇到错误。

    下面的错误(first part & second part)表明您有一个二维球体索引。

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

    因此,当您更改为{"loc": {"coordinates": [23, 25] }} 时,无法构建二维球体索引。

    您可以验证索引。 db.users.getIndexes()

    删除 2d 索引(仍然存在是为了向后兼容)。二维球体索引同时支持旧坐标(例如{"loc":[23, 25]})和地理坐标。

    db.users.dropIndex( "loc_2d" ) 
    

    当 2d 球体索引为集合重建索引时,这应该可以工作。

    如果上述解决方案不起作用,请删除集合并重新开始。

    db.users.drop()
    

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多