【问题标题】:SimpleSchema match any type but nullSimpleSchema 匹配除 null 之外的任何类型
【发布时间】:2016-04-30 18:40:12
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript meteor simple-schema


    【解决方案1】:

    您可以将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
    

    排除 one 值的更一般的解决方案是:

    const notValuePattern =
      unwantedValue => Match.Where(val => val !== unwantedValue))
    

    其中的用法与上面类似:

    Match.test(42, notValuePattern(null)) // true
    

    请注意,由于使用了identity operator ===,它将特别是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... 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
    

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 2012-01-12
      • 1970-01-01
      • 2016-01-16
      • 2023-03-13
      相关资源
      最近更新 更多