在mongoose模式上应用2dsphere索引是否强制要求位置字段?

我有一个mongoose模式和模型定义如下:

var mongoose = require('mongoose') , Schema = new mongoose.Schema({ email: { index: { sparse: true, unique: true }, lowercase: true, required: true, trim: true, type: String }, location: { index: '2dsphere', type: [Number] } }) , User = module.exports = mongoose.model('User', Schema); 

如果我尝试:

 var user = new User({ email: 'user@example.com' }); user.save(function(err) { if (err) return done(err); should.not.exist(err); done(); }); 

我收到错误消息:

 MongoError: Can't extract geo keys from object, malformed geometry?:{} 

尽pipe这个模式中的位置字段不是必需的,但它似乎也是这样的。 我已经尝试添加default: [0,0] ,它避免了这个错误,但它似乎有点破解,因为这显然不是一个好的默认值,理想情况下,架构不会要求用户有一个位置一直。

用MongoDB / mongoose做地理空间索引意味着被索引的字段是必需的吗?

默认情况下,声明数组的属性接收一个默认的空数组来处理。 MongoDB已经开始validationgeojson字段并大声说出空数组。 解决方法是向检查此scheme的模式添加预保存钩子,并首先修复文档。

 schema.pre('save', function (next) { if (this.isNew && Array.isArray(this.location) && 0 === this.location.length) { this.location = undefined; } next(); }) 

对于mongoose3.8.12,你设置了默认值:

 var UserSchema = new Schema({ location: { 'type': {type: String, enum: "Point", default: "Point"}, coordinates: { type: [Number], default: [0,0]} }, }); UserSchema.index({location: '2dsphere'});