SimpleSchema 匹配除 null 以外的任何类型

SimpleSchema match any type but null

我打算制作一个集合来保存不同的应用程序范围的设置,比如今天登录的用户数量、Google 分析跟踪 ID 等。所以我制作了一个这样的模式:

options_schema = new SimpleSchema({
    key: {
        type: String,
        unique: true
    },
    value: {
    },
    modified: {
        type: Date
    }
});

现在的主要问题是我希望 value 是任何类型:数字、字符串、日期,甚至是自定义对象。虽然它必须存在,但不能是 null.

当然,它会因为不指定类型而生气。有解决办法吗?

您可以将 Match patterns 用于您的字段 type,这样您几乎可以做任何事情:

const notNullPattern = Match.Where(val => val !== null)
value : {
  type : notNullPattern
}

(见Arrow functions

请注意,这将允许 null 以外的所有内容,包括 undefined
以这种方式定义模式允许您在应用程序的任何地方使用它们,包括 in check :

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

注意由于使用了identity operator === it will notably fail for NaN:

Match.test(NaN, notValuePattern(NaN)) // true :(

解决方案可能是:

const notValuePattern =
  unwantedValue => Match.Where(val => Number.isNaN(unwantedValue)?
    !Number.isNaN(val)
    : val !== unwantedValue
  )

如果您想要一个解决方案来排除模式中的某些特定值(与 Match.OneOf 相反),您可以使用以下方法:

const notOneOfPattern = (...unwantedValues) => 
  Match.Where(val => !unwantedValues.includes(val)
)

这使用 Array.prototype.includes and the ... spread operator。使用如下:

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