Michele Spina
Michele Spina

Reputation: 1121

Mongoose - 2dsphere index - howto

I am working with Node.js.How can I configure a 2dsphere index for a Polygon on the schema of Mongoose?

I have tried with it:

  location_2dsphere: {
      type: { type: String }
      , coordinates: []
  },

But it doesn't work!

Upvotes: 1

Views: 1624

Answers (2)

RomanistHere
RomanistHere

Reputation: 904

On top level:

db.collections.<yourcollection>.createIndex({ <location_field> : "2dsphere" })

where db = mongoose.connection

Notice there is a "collections" property before collection itself. If it's not working, check db object in console.log:

console.log(db)

Upvotes: 0

nevi_me
nevi_me

Reputation: 2730

this is how you do it

location_2dsphere: {
  'type': { type: String },
    coordinates: []
  }

So the key thing is to make the first type to be 'type'

Then remember to create a 2dsphere index on your field!

In Mongoose, when you want to name a field as type or any other reserved field, just force string conversion by using the parentheses.

Upvotes: 2

Related Questions