David Tzoor
David Tzoor

Reputation: 1077

Using geoJSON in mongoose schema and use it in a query

I'm new to mongoDB and the usage of geoJSON within it.

I have the following schema I created using the mongoose module:

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);

I used a simple Number type to represent to longitude and latitude inside a sub object within the schema.

I don't know if this is the way to go about it. I want it to be saved as a geoJSON object and then run queries on this object.

Upvotes: 1

Views: 4344

Answers (2)

Kegham K.
Kegham K.

Reputation: 1614

You can also do it this way:

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

Check this tutorial: How to use geospatial indexing in mongoDb

Upvotes: 2

throrin19
throrin19

Reputation: 18197

I recommand you to see the mongoDB part for geolocation datas : http://docs.mongodb.org/manual/core/2d/

To store longitude, latitude, MongoDB take you the correct data structure to save items :

To store location data as legacy coordinate pairs, use an array or an embedded document. When possible, use the array format:

loc : [ < longitude > , < latitude > ]

Consider the embedded document form:

loc : { lng : , lat : }

Arrays are preferred as certain languages do not guarantee associative map ordering.

For all points, if you use longitude and latitude, store coordinates in longitude, latitude order.

On your shema, change

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

By :

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

Then you should add a 2dindex for your field start_coords to use all mongoDB geospatial queries :

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

EDIT It's important to set min and max if your longitude and latitude is not a real lng/lat (for example if you could use 2dindexes in a orthonormal map)

Now you can use all geospatial query operators : http://docs.mongodb.org/manual/reference/operator/query-geospatial/

Upvotes: 3

Related Questions