【发布时间】:2021-04-29 08:30:53
【问题描述】:
如何在架构中的值之一,布尔和数字两种数据类型?
【问题讨论】:
标签: javascript mongoose
如何在架构中的值之一,布尔和数字两种数据类型?
【问题讨论】:
标签: javascript mongoose
我认为您要问的是是否有一种方法可以拥有一个可以是 Number 或 Boolean 类型的字段。如果是这种情况,您可以使用自定义 SchemaType 来完成此操作(请参阅 https://mongoosejs.com/docs/customschematypes.html 上有关此主题的 mongoose 文档)。代码是这样的:
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;
【讨论】: