我正在使用mongoose v4.8.0
,
mongo v3.4.1
,node v6.9.1
我有这个架构:
var UserSchema = new Schema({
volAddressCoords: { 'type': {type: String, default: "Point"},
coordinates: { type: [Number],
default: [37.9800927,23.73151580]},
index: {type: String, default: '2dsphere'}}
(...)
})
用户选中一个复选框,提交一个表单,如果是,则这是req.body:
{ volAddress: null,
volAddressCoords: [],
comRange: null,
isVolunteer: null }
这是false时抛出的错误(所有字段都是emtpy): (为方便起见,所有错误均被截断)
{ ValidationError: User validation failed
errors:
{ volAddressCoords:
{ CastError: Cast to Object failed for value "[]" at path "volAddressCoords"
message: 'Cast to Object failed for value "[]" at path "volAddressCoords"',
name: 'CastError',
stringValue: '"[]"',
kind: 'Object',
value: [],
path: 'volAddressCoords',
reason: undefined },
'volAddressCoords.type':
{ ValidatorError: `,` is not a valid enum value for path `volAddressCoords.type`.
message: '`,` is not a valid enum value for path `volAddressCoords.type`.',
name: 'ValidatorError',
properties: [Object],
kind: 'enum',
path: 'volAddressCoords.type',
value: [Object] } },
message: 'User validation failed',
name: 'ValidationError' }
真实的身体:
{ volAddress: '2307 Princes Highway, Heywood, Βικτώρια, Αυστραλία',
volAddressCoords: [ 141.61755859999994, -38.1103413 ],
comRange: 4,
isVolunteer: true }
复选框为true时出错:
{ ValidationError: User validation failed
errors:
{ volAddressCoords:
{ CastError: Cast to Object failed for value "[ 141.61755859999994, -38.1103413 ]" at path "volAddressCoords"
message: 'Cast to Object failed for value "[ 141.61755859999994, -38.1103413 ]" at path "volAddressCoords"',
name: 'CastError',
stringValue: '"[ 141.61755859999994, -38.1103413 ]"',
kind: 'Object',
value: [Object],
path: 'volAddressCoords',
reason: undefined },
'volAddressCoords.type':
{ ValidatorError: `,` is not a valid enum value for path `volAddressCoords.type`.
message: '`,` is not a valid enum value for path `volAddressCoords.type`.',
name: 'ValidatorError',
properties: [Object],
kind: 'enum',
path: 'volAddressCoords.type',
value: [Object] } },
message: 'User validation failed',
name: 'ValidationError' }
我也尝试了另一个SO问题Does applying a 2dsphere index on a mongoose schema force the location field to be required?中提到的代码,但同样的错误发生了:
UserSchema.pre('patch', function (next) {
if (this.isNew && Array.isArray(this.volAddressCoords) && 0 === this.volAddressCoords.length) {
this.volAddressCoords = undefined;
}
next();
});
为了工作,我该怎么办?
答案 0 :(得分:0)
我的坏,我正在将对象投射到一个字符串......
volAddressCoords: {type: Object,
properties: {
type: {
type: String,
enum: 'Point',
default: 'Point'
},
coordinates: {
type: [Number],
default: [0, 0]
},
index: {type: String, default: '2dsphere'}
}}