2013-05-05 12 views
10

我定义为猫鼬架构和模型如下:在猫鼬模式上应用2dsphere索引是否强制要求位置字段?

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: '[email protected]' }); 

user.save(function(err) { 
    if (err) return done(err); 

    should.not.exist(err); 
    done(); 
}); 

我收到错误消息:

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

尽管在此位置字段架构不是必需的,它似乎反正是这样。我曾尝试添加default: [0,0],它避免了这个错误,但它看起来有点像黑客,因为这显然不是一个好的默认设置,理想情况下,架构不需要用户随时都有位置。

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

回答

14

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

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

这是不是可以添加到猫鼬为{类型:[序号],索引: '2dsphere'}领域,所以它会自动处理? – 2013-08-21 17:14:47

+3

绝对:https://github.com/LearnBoost/mongoose/issues/1668 – aaronheckmann 2013-08-27 21:00:46

+0

太棒了,欢呼亚伦 – 2013-08-28 06:14:04

31

对于猫鼬3.8.12,你设置的默认值: