问题描述
我的猫鼬模式和模型定义如下:
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?:{}
尽管此模式中的位置字段不是必需的,但无论如何似乎仍在起作用.我尝试添加确实避免了此错误的default: [0,0]
,但是似乎有点hack,因为这显然不是一个很好的默认值,理想情况下,该架构不需要用户始终有位置. /p>
使用MongoDB/mongoose进行地理空间索引是否暗示需要建立索引的字段?
默认情况下,声明为数组的属性会接收默认的空数组以供使用. MongoDB已经开始验证geojson字段,并大喊空数组.解决方法是在架构中添加预保存钩子,以检查这种情况并首先修复文档.
schema.pre('save', function (next) {
if (this.isNew && Array.isArray(this.location) && 0 === this.location.length) {
this.location = undefined;
}
next();
})
I have a mongoose schema and model defined as follows:
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);
If I attempt:
var user = new User({ email: 'user@example.com' });
user.save(function(err) {
if (err) return done(err);
should.not.exist(err);
done();
});
I receive the error message:
MongoError: Can't extract geo keys from object, malformed geometry?:{}
Despite the location field in this schema not being required, it seems to be acting as such anyways. I have tried adding default: [0,0]
which does circumvent this error, however it seems like a bit of a hack, as this is clearly not a good default, and ideally the schema would not require the user to have a location at all times.
Do geospatial indexes with MongoDB / mongoose imply that the field being indexed is required?
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();
})
这篇关于在猫鼬模式上应用2dsphere索引是否会强制需要location字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!