Reputation: 2142
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 mongoose so I'm just gonna ask it here.
I first create my model:
var eventSchema = mongoose.Schema({
name : String,
creator : String,
location : { type: [Number], index: '2dsphere'},
});
Then I try to add it to my database:
var newevent = new event({
name: name,
creator: tokenUser,
location : { type: "Point", coordinates: [longitude, latitude] },
});
When I look in my database everything is stored except the location ...
Upvotes: 8
Views: 13399
Reputation: 331
This way i find it simpler.
const GeoSchema = mongoose.Schema({
type: {
type: String,
default: "Point",
},
coordinates: {
type: [Number], //the type is an array of numbers
index: "2dsphere"
}
})
const EventSchema = mongoose.Schema({
name: String,
creator: String,
location: GeoSchema
})
And when entering data
Event({
name,
creator,
location: { type: "point", coordinates: [longitude, latitude] }
})
Upvotes: 2
Reputation: 2210
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.
Upvotes: 1
Reputation: 2142
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 ] },
Upvotes: 10
Reputation: 1406
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.
Upvotes: 3