Nik*_*osh 11 mongoose mongodb node.js
我有一个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);
Run Code Online (Sandbox Code Playgroud)
如果我尝试:
var user = new User({ email: 'user@example.com' });
user.save(function(err) {
if (err) return done(err);
should.not.exist(err);
done();
});
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
MongoError: Can't extract geo keys from object, malformed geometry?:{}
Run Code Online (Sandbox Code Playgroud)
尽管此模式中的位置字段不是必需的,但它似乎仍然如此.我已经尝试添加default: [0,0]
哪个可以绕过这个错误,但是它似乎有点像黑客,因为这显然不是一个好的默认值,理想情况下,架构不需要用户始终拥有一个位置.
使用MongoDB/mongoose的地理空间索引是否意味着需要索引的字段?
use*_*143 41
对于mongoose 3.8.12,您可以设置默认值:
var UserSchema = new Schema({
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
default: [0, 0],
}
}
});
UserSchema.index({location: '2dsphere'});
Run Code Online (Sandbox Code Playgroud)
aar*_*ann 17
默认情况下,声明为数组的属性接收要使用的默认空数组.MongoDB已经开始验证geojson字段并对空数组大喊大叫.解决方法是在架构中添加一个预保存挂钩,以检查此场景并首先修复文档.
schema.pre('save', function (next) {
if (this.isNew && Array.isArray(this.location) && 0 === this.location.length) {
this.location = undefined;
}
next();
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13028 次 |
最近记录: |