如何在模式中的值之一,2个数据类型布尔和数字?
我想你问的是,是否有一种方法可以有一个字段的类型是数字或布尔。如果是这种情况,您可以使用自定义SchemaType完成此任务(请参阅有关此主题的mongoose文档https://mongoosejs.com/docs/customschematypes.html)。代码应该是这样的:
class BoolOrNumber extends mongoose.SchemaType {
constructor(key, options) {
super(key, options, 'BoolOrNumber');
}
// `cast()` takes a parameter that can be anything. You need to
// validate the provided `val` and throw a `CastError` if you
// can't convert it.
cast(val) {
let _val = Number(val);
if (isNaN(_val) && val !== true && val !== false) {
throw new Error('BoolOrNumber: ' + val + ' must be a number or boolean');
}
return _val;
}
}
// Don't forget to add `BoolOrNumber` to the type registry
mongoose.Schema.Types.BoolOrNumber = BoolOrNumber;