【问题标题】:nodejs and mongodb: how model a geolocation?nodejs 和 mongodb:如何建模地理定位?
【发布时间】:2018-01-25 13:09:26
【问题描述】:

我正在开发一个 API 来存储位置,包括它们的坐标,但我不知道对它们进行建模。 我应该去吗

latitude: { 
 type: Float 
},
longitude: {
 type: Float 
},

或者有没有办法将它们建模为一个数组,比如 [43.95 , -26.75]? 我想稍后过滤它们的距离。

【问题讨论】:

  • 我找到了一些关于它的文档。也许这会有所帮助:docs.mongodb.com/manual/reference/operator/query/type
  • mongodb 是弱模式,你可以认为它是一种 json 存储,对于坐标,你可以将它们存储为对象:{lat: xxx, lng: xxx} 或者你可以存储它们作为数组 [lat, lng]。
  • 这真是见仁见智。但是,如果您打算查询数据库中的“最近”等,那么我建议存储在 supported format 中,最好是 GeoJSON。

标签: node.js mongodb express mongoose


【解决方案1】:

最近我从事地理定位的工作,我想我可以回答你的问题,为时已晚,但这可能会帮助其他正在寻找解决方案的人。

location: {
  type: {
    type: String,
    default: 'Point',
  },
  coordinates: [Number], // [22.2475, 14.2547]  [longitude, latitude]
};

以上述方式,我们必须在我们的模式定义中引入这个属性。然后我们需要在我们的集合中创建一个 2dsphere 索引,如下所示:-

db.collection.createIndex( { location : "2dsphere" } )

就是这样,现在您可以根据位置触发查询

db.collection.aggregate([
        {
          $geoNear: {
            near: {
                type: 'Point',
                coordinates: [22.4568, 14.5412],        
            },
            key: 'location',
            distanceField: 'distance', // in meter
            spherical: true,
          },
        }
        ])

【讨论】:

    【解决方案2】:

    最好将它们存储为 GeoJSOn 数据,然后通过应用 2dsphere 索引很容易查询。

    这种类型的存储的一个例子是:-

    "geolocation" : {
             "type":"Point",
             "coords":[-71.1410879999999960,42.4051060000000040]      
        }
    

    架构格式:-

    geolocation: {
        type: { type: String },
        coordinates: [Number],
    }
    

    【讨论】:

    • 所以,我的 LocationModel.js 应该是这样的:'locationName: { type: String, Required: 'Enter the name of the location.' }, description: { type: String, required: '输入位置描述。' }, "geolocation" : { type: String, coords:[float,float] }' ?
    • 我已经安装了 GeoJSOn 但不知道如何使用它。
    • 这样我可以输入像 45.33 这样的坐标,但是 GeoJSOn 使用像 45,33(意思是纬度 45 和经度 33)。也许是数字,数字?
    • 我不能以这种方式提交 2 个号码。
    • 要存储浮点数,您必须使用 Number 类型。请参考这个答案stackoverflow.com/questions/5605551/…
    【解决方案3】:

    使用MongoDB's Geospatial Data

    在 MongoDB 中,您可以将地理空间数据存储为 GeoJSON 对象或传统坐标对。

    那么你可以使用Geospatial Queries

    【讨论】:

    • 我应该如何为我的架构建模?
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2013-12-31
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多