保存在mongodb的位置

问题描述 投票:4回答:2

我正试图在我的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:[email protected]
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": "[email protected]",
        "password": "t12345",
        "name": "Igor",
        "_id": "5a311c016d15fc235895bef3",
        "created_at": "2017-12-13T12:24:33.493Z",
        "loc": {
            "coordinates": [],
            "type": "Point"
        },
        "type": true,
        "__v": 0
    }
}
node.js mongodb mongoose geospatial
2个回答
4
投票

您可以在集合中同时拥有2d和2dsphere索引。

下面的error表示你有一个2d索引。

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

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

下面的错误(first partsecond part)表示你有一个2d球体索引。

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

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

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

删除2d索引(仍为了向后兼容性)。 2d球体索引支持传统坐标(例如{"loc":[23, 25]})和地理坐标。

db.users.dropIndex( "loc_2d" ) 

当2d球体索引重建索引以进行收集时,这应该有效。

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

db.users.drop()

1
投票
  1. 您所有文档的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" },
  2. 确保清除了一些错误格式的文档。保持所有文档遵循有效格式。
© www.soinside.com 2019 - 2024. All rights reserved.