Does applying a 2dsphere index on a mongoose schema force the location field to be required?
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'});
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();
})