我在pre('validate')挂钩期间执行操作时遇到问题。我需要做一些预验证(例如,确保填充了2个不同字段中的至少一个,但不一定两者都是。)
const AccessorySchema = new Schema({
accessory: {
type: String,
required: true,
},
category: {
type: String,
required: true,
enum: [
'Offense',
'Defence',
'Miscellaneous'
]
},
space: {
type: Number,
required: true,
validate: {
validator: Number.isInteger,
message: 'Space must be an integer'
}
},
priceFixed: {
type: Number,
required: false,
validate: {
validator: Number.isInteger,
message: 'Fixed Price must be an integer'
}
},
priceMultiplier: {
type: [Schema.Types.Mixed],
required: false
},
weightFixed: {
type: Number,
required: false,
validate: {
validator: Number.isInteger,
message: 'Fixed Weight must be an integer'
}
},
weightMultiplier: {
type: [Schema.Types.Mixed],
required: false
},
vehicles: {
type: [String],
required: true,
enum: ["car","cycle"]
}
});
AccessorySchema.pre('validate', (next) => {
console.log(this);
next();
});
我发送这个对象:
{
accessory: "some name",
category: "Miscellaneous",
priceMultiplier: [3,5],
weightMultiplier: [3,5],
space: 0,
vehicles: ["car"]
}
此日志{}
并填充mongo数据库。但我无法在预验证中检查任何属性。
mongoose版本是^ 4.7.7,nodejs 6.10.2,mongodb版本是3.2.9
如何访问预验证挂钩中的数据?
答案 0 :(得分:1)
不使用箭头功能,它不会绑定上下文。 将您的代码更改为
AccessorySchema.pre('validate', function(next){
console.log(this);
next();
});