Whenever I try to store a location in my mongodb it doesn\'t show, so I guess I\'m doing something wrong. I can\'t find any documentation on how to store a location in mongo
I fixed it myself.
I did this in my model:
loc : { type: {type:String}, coordinates: [Number]},
Underneath I made it a 2dsphere index.
eventSchema.index({loc: '2dsphere'});
And to add data to it:
loc: { type: "Point", coordinates: [ longitude, latitude ] },
Looks like your comment is correct (maybe), but the syntax for the index schemetype
here: http://mongoosejs.com/docs/api.html#schematype_SchemaType-index
It only accepts Object, Boolean, String
The correct syntax should be I think
var eventSchema = new Schema({
location: { type: [Number], index: { type: '2dsphere', sparse: true}}
)
based on the example in the docs.
Citing from the mongoose documentation for defining coordinates in schema, I'd like to make a tiny addition to @Laurenswuyts' answer for the 'type' property.
const exampleSchema = new mongoose.Schema({
location: {
type: {
type: String, // Don't do `{ location: { type: String } }`
enum: ['Point'], // 'location.type' must be 'Point'
required: true
},
coordinates: {
type: [Number],
required: true
}
}
});
Instead of leaving the 'type' property of 'location' open-ended with 'type: String', defining it with a single option enum 'Point' and setting 'required' to 'true' makes the code more robust. Then you would create index and add data the same way @Laurenswuyts did.