最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

保存在mongodb的位置

运维笔记admin9浏览0评论

保存在mongodb的位置

保存在mongodb的位置

我正试图在我的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
    }
}
回答如下:

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

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

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

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

下面的错误(first part和second 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()

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论