【发布时间】:2020-02-17 16:58:21
【问题描述】:
我想将一个变量绑定到一个回调函数,但 mongoose 已经在该函数中嵌入了一个名为 val 的参数。当我想用 .bind() 将另一个值绑定到回调函数时,我丢失了原始的 val 属性。有没有办法我可以保留原始参数并将我的变量与 .bind() 添加到它? 下面是一个例子。
// gets val parameter from validator
const maxLengthValidator = (val: string): boolean => {
if (val.length > 255) return false;
return true;
};
const userSchema = new Schema({
email: {
type: String,
required: true,
// unique: true
validate: [
{
validator: maxLengthValidator, // includes a val attribute from post request
msg: 'too short'
},
]
},
password: {
type: String,
required: true
}
});
export default model('User', userSchema);
我想做什么:
// gets val parameter from validator
const maxLengthValidator = (val: string, boundary: number): boolean => {
if (val.length > boundary) return false;
return true;
};
...
validate: [
{
validator: maxLengthValidator.bind(this, 255), // doesn't work, would need to specify the string for the val parameter
msg: 'too short'
},
]
...
所以我可以在验证器对象中设置一个最大长度。
【问题讨论】:
-
为什么不直接做
validator: (val: string): boolean => maxLengthValidator(val, 255)? -
或者,您可以交换
maxLengthValidator的参数顺序并使用现有的绑定调用。或者使用const maxLengthValidator = (boundary: number): (string) => boolean => (val: string): boolean => {和validator: maxLengthValidator(255)之类的柯里化 -
有时你只是看不到明显的:D 谢谢大家!
标签: javascript mongodb typescript validation mongoose