I have a mongoose schema and model defined as follows:
var mongoose = require(\'mongoose\')
, Schema = new mongoose.Schema({
email: {
index:
For mongoose 3.8.12, you set the default value:
var UserSchema = new Schema({
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
default: [0, 0],
}
}
});
UserSchema.index({location: '2dsphere'});
The only way I have resolved this issue was changing the index type from
GEO:{
type: [Number],
index: '2dsphere'
}
to
GEO:{
type: [Number],
index: '2d'
}
It was a nightmare
The correct way to create a schema with geolocation and run geospartial queries was
var UserSchema = new Schema({
location: {
type: {
type: String,
enum: ["Point"], // 'location.type' must be 'Point'
},
coordinates: {
type: [Number]
}
}
});
UserSchema.index({location: '2dsphere'});
Be careful this is important to do, the index 2dsphere in the location.coordinates, if you want to run geospartial queries!
By default, a property declared an array receives a default empty array to work with. MongoDB has started validating geojson fields and yells about empty arrays. The work around is to add a pre save hook to the schema that checks for this scenario and fixes up the document first.
schema.pre('save', function (next) {
if (this.isNew && Array.isArray(this.location) && 0 === this.location.length) {
this.location = undefined;
}
next();
})