在mongoose模式中使用geoJSON并在查询中使用它

我是新来的mongoDB和其中的geoJSON的使用。

我有我使用mongoose模块创build的以下架构:

var mongoose = require('mongoose'); var hikeSchema = mongoose.Schema({ name: String, area: String, length: Number, time: String, Difficulty: { type : Number, min : 0 , max :5 }, start_coord: { lon: Number, lat: Number }, rank_count: Number, avg_overall_rating: { type : Number, min : 0 , max :5 }, completed_count: Number, description: String, ranking_pages: [ mongoose.Schema.Types.ObjectId ] }); module.exports = mongoose.model('Hike', hikeSchema); 

我用一个简单的Numbertypes来表示模式内的一个子对象内的经度和纬度。

我不知道这是否是这样的。 我希望它被保存为一个geoJSON对象,然后在这个对象上运行查询。

我build议您查看地理位置数据的mongoDB部分: http ://docs.mongodb.org/manual/core/2d/

为了存储经度,纬度,MongoDB带你正确的数据结构来保存项目:

要将位置数据存储为传统坐标对,请使用数组或embedded式文档。 如果可能,请使用数组格式:

loc:[<经度>,<纬度>]

考虑embedded式文件格式:

loc:{lng:,lat:}

数组是首选的,因为某些语言不保证关联映射sorting。

对于所有点,如果使用经度和纬度,则按经度,纬度顺序存储坐标。

在你的身上,改变

 start_coord: { lon: Number, lat: Number }, 

借:

 start_coord: { lng: Number, lat: Number }, 

然后,您应该为您的字段start_coords添加2dindex以使用所有mongoDB地理空间查询:

 db.collection.ensureIndex( { start_coord : "2d" } , { min : <l ower bound > , max : < upper bound > } ) 

编辑如果您的经度和纬度不是真正的lng / lat(例如,如果您可以在正交地图中使用2dindexes),设置min和max是很重要的。

现在,您可以使用所有地理空间查询运算符: http : //docs.mongodb.org/manual/reference/operator/query-geospatial/

你也可以这样做:

 start_coord: { type: [Number], // [<longitude>, <latitude>] index: '2d' // create the geospatial index } 

检查本教程: 如何在mongoDb中使用地理空间索引