Does applying a 2dsphere index on a mongoose schema force the location field to be required?

后端 未结 4 599
长发绾君心
长发绾君心 2020-12-15 23:17

I have a mongoose schema and model defined as follows:

var mongoose = require(\'mongoose\')
  , Schema = new mongoose.Schema({
      email: {
        index:          


        
相关标签:
4条回答
  • 2020-12-15 23:47

    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'});
    
    0 讨论(0)
  • 2020-12-15 23:50

    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

    0 讨论(0)
  • 2020-12-15 23:51

    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!

    0 讨论(0)
  • 2020-12-16 00:03

    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();
    })
    
    0 讨论(0)
提交回复
热议问题