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

后端 未结 4 601
长发绾君心
长发绾君心 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-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();
    })
    

提交回复
热议问题