0

My Schema is as follows:

mongoose = require 'mongoose'
ObjectId  = mongoose.Schema.ObjectId

CheckinSchema = new mongoose.Schema
  text:
    type: String, required: true
  location_latLong:
    lat:
      type: Number
    lon:
      type: Number
  location_country:
    type: String
  addedOn:
    type: Date
    default: Date.now

CheckinSchema.index
  location_latLong: '2d'

exports.CheckinSchema = CheckinSchema

The Model is generated separately. I get an error however when running a query. The error is:

count fails:{ errmsg: "exception: can't find special index: 2d for: { location_latLong: { $wi...", code: 13038, ok: 0.0 }

My query is:

{ location_latLong: { '$within': { '$box': [[ '-100', '-100' ],[ '100', '100' ]] } } }

So my question is.... what gives? How can I properly do Geospatial indexing in Mongoose (using Node.js)

0

1 Answer 1

2

THis is because you have specified the wrong order in your geo index, Since mongodb is based on GeoJSON, its recommented to have the longitude field first

instead this

location_latLong:
    lat:
      type: Number
    lon:
      type: Number

use this

location_latLong:
    lon:
      type: Number
    lat:
      type: Number

The names you assign to a location object (lon,lat keys) are completely ignored, only the ordering is detected.

In mongodb geospatial page, its recommended in multiple places

By default, the index assumes you are indexing longitude/latitude and is thus configured for a [-180..180) value range

and

The code assumes that you are using decimal degrees in (longitude, latitude) order. This is the same order used for the GeoJSON spec. Using (latitude, longitude) will result in very incorrect results, but is often the ordering used elsewhere, so it is good to double-check. The names you assign to a location object (if using an object and not an array) are completely ignored, only the ordering is detected.

I have already answered this before.

Cheer

Sign up to request clarification or add additional context in comments.

1 Comment

Heads up... apparently MongoDB lies! "location_latLong" : { "lon" : -3.202774, "lzt" : 55.954155 } is what was saved in my DB (notice the ordering) but when I use lat, then the lat is first. Bottom line - it does do ordering of keys based on alpha sorting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.