我打算制作一个集合来保存不同的应用程序范围的设置,例如,今天登录的用户数量,Google分析跟踪ID等等。所以我制作了这样的架构:
options_schema = new SimpleSchema({
key: {
type: String,
unique: true
},
value: {
},
modified: {
type: Date
}
});
现在主要问题是我希望value
属于任何类型:Number,String,Date,甚至是自定义对象。虽然它必须存在,但不能是null
。
但当然,对于不指定类型感到愤怒。有解决方法吗?
答案 0 :(得分:4)
您可以将[{3}}用于您的字段' type
允许你做几乎任何事情:
const notNullPattern = Match.Where(val => val !== null)
value : {
type : notNullPattern
}
请注意,这将允许null
以外的所有内容,包括undefined
通过这种方式定义模式,您可以在应用程序的任何位置使用它们,包括Arrow functions:
check({
key : 'the key',
modified : Date.now(),
value : {} // or [], 42, false, 'hello ground', ...
}, optionsSchema)
Match.test(undefined, notNullPattern) //true
Match.test({}, notNullPattern) //true
Match.test(null, notNullPattern) //false
排除一个值的更通用解决方案只是:
const notValuePattern =
unwantedValue => Match.Where(val => val !== unwantedValue))
使用方法与上述类似:
Match.test(42, notValuePattern(null)) // true
请注意,由于使用了in check
,因此会显着identity operator ===
:
Match.test(NaN, notValuePattern(NaN)) // true :(
解决方案可能是:
const notValuePattern =
unwantedValue => Match.Where(val => Number.isNaN(unwantedValue)?
!Number.isNaN(val)
: val !== unwantedValue
)
如果您想要一个解决方案来排除模式中的某些特定值(与fail for NaN
相反),您可以使用以下内容:
const notOneOfPattern = (...unwantedValues) =>
Match.Where(val => !unwantedValues.includes(val)
)
这使用Match.OneOf
和Array.prototype.includes
。使用方法如下:
Match.test(42, notOneOfPattern('self-conscious whale', 43)) // true
Match.test('tuna', notOneOfPattern('tyranny', 'tuna')) // false
Match.test('evil', notOneOfPattern('Plop', 'kittens')) // true
const disallowedValues = ['coffee', 'unicorns', 'bug-free software']
Match.test('bad thing', notOneOfPattern(...disallowedValues)) // true