Javascript SimpleSchema匹配除null以外的任何类型
我计划创建一个集合,以保存不同的应用程序范围设置,例如,今天登录的用户数量、Google analytics跟踪ID等。因此,我创建了一个如下模式:Javascript SimpleSchema匹配除null以外的任何类型,javascript,meteor,simple-schema,Javascript,Meteor,Simple Schema,我计划创建一个集合,以保存不同的应用程序范围设置,例如,今天登录的用户数量、Google analytics跟踪ID等。因此,我创建了一个如下模式: options_schema = new SimpleSchema({ key: { type: String, unique: true }, value: { }, modified: { type: Date } }); 现在主要的问题是,我希望
options_schema = new SimpleSchema({
key: {
type: String,
unique: true
},
value: {
},
modified: {
type: Date
}
});
现在主要的问题是,我希望值可以是任何类型:数字、字符串、日期,甚至自定义对象。虽然它必须存在,但不能为null
但它当然会因为没有指定类型而生气。有解决方法吗?您可以使用字段类型来执行几乎所有操作:
const notNullPattern = Match.Where(val => val !== null)
看
请注意,这将允许除null以外的所有内容,包括未定义的内容。
通过这种方式定义模式,您可以在应用程序中的任何地方使用它们,包括:
排除一个值的更一般的解决方案是:
const notValuePattern =
unwantedValue => Match.Where(val => val !== unwantedValue))
其用途与上述类似:
Match.test(42, notValuePattern(null)) // true
请注意,由于使用,it将显著:
解决办法可以是:
const notValuePattern =
unwantedValue => Match.Where(val => Number.isNaN(unwantedValue)?
!Number.isNaN(val)
: val !== unwantedValue
)
如果您希望解决方案排除模式中的某些特定值,则可以使用以下方法:
const notOneOfPattern = (...unwantedValues) =>
Match.Where(val => !unwantedValues.includes(val)
)
这使用了和。使用方法如下:
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
您可以使用字段的类型来执行几乎所有操作:
const notNullPattern = Match.Where(val => val !== null)
看
请注意,这将允许除null以外的所有内容,包括未定义的内容。
通过这种方式定义模式,您可以在应用程序中的任何地方使用它们,包括:
排除一个值的更一般的解决方案是:
const notValuePattern =
unwantedValue => Match.Where(val => val !== unwantedValue))
其用途与上述类似:
Match.test(42, notValuePattern(null)) // true
请注意,由于使用,it将显著:
解决办法可以是:
const notValuePattern =
unwantedValue => Match.Where(val => Number.isNaN(unwantedValue)?
!Number.isNaN(val)
: val !== unwantedValue
)
如果您希望解决方案排除模式中的某些特定值,则可以使用以下方法:
const notOneOfPattern = (...unwantedValues) =>
Match.Where(val => !unwantedValues.includes(val)
)
这使用了和。使用方法如下:
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