I have two models, Location
and Event
.
class Event
include Mongoid::Document
field :name, type: String
belongs_to :location
index({'location.coordinates' => '2d'}, {unique: true}) # I added this later on because I had an error when querying on location.coordinates
end
class Location
include Mongoid::Document
field :coordinates, type: Array
index({coordinates: '2d'}, {unique: true})
has_many :events
end
Now if I create an Event
with an associated location
Location.create({coordinates: [40.7127837, -74.0059413]})
Event.create({name: "foo", location: Location.first})
How can I query events near a specific location? I tried this:
Event.where('location.coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first
but it returns no results, while
Location.where('coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first
returns the Location
object created earlier.
What am I doing wrong?