【问题标题】:How to pass schema type: Object's key rules如何传递模式类型:对象的关键规则
【发布时间】:2021-08-06 07:16:48
【问题描述】:

我正在尝试了解如何使用 Meteor-Collection2 验证对象。我可以在下面的代码中更好地解释:

// This is the object structure to validate
// const obj = {
//   name: 'Test',
//   active: true,
// }

Test.schemaObj = {
  someOtherName: {
    type: String, // Not the same as obj variable
  },
  testType: {
    type: Object,
    // The goal is to define rules for validation for 
    // things that this will contain.
  },
  // Inside the object: {
  //     type: String,
  //     required: true,
  //},
  // Inside the object: {
  //     type: Boolean,
  //     required: true,
  //},
};

我了解 required 在未定义时会自动设置为 true。

我的目的是基本上列出对象必须具有的所有键及其验证规则。我知道对象数组是如何工作的,只是不确定对象验证的语法是什么。

我浏览了文档和堆栈溢出,但我无法在网上找到明确显示语法的任何地方。

我确信我缺少一些基本的东西,但是我是新手,我希望有人可以帮助我。

【问题讨论】:

    标签: javascript mongodb meteor meteor-collection2 simpl-schema


    【解决方案1】:

    我知道您要验证testType 对象。那么有两种方式:

    1. 您可以添加黑盒:true,这将允许该对象具有任何结构;

    2. 你需要定义对象的每个属性,像这样:

    Test.schemaObj = {
      someOtherName: {
        type: String, // Not the same as obj variable
      },
      testType: {
        type: Object,
        // The goal is to define rules for validation for 
        // things that this will contain.
      },
      "testType.attribute1": {
           type: String,
           required: true,
      },
      "testType.attribute2": {
          type: Boolean,
          required: true,
      },
    };
    
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2012-07-20
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多