Search code examples
javascriptmongodbmeteormeteor-collection2simpl-schema

How to pass schema type: Object's key rules


I am trying to understand how to validate, an object using Meteor-Collection2. I can better explain in the code below:

// 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,
  //},
};

I understand that required is automatically set to true when not defined.

My purpose is to basically list all the keys that the object must have and their validation rules. I know how an array of object works, I am just not sure what the syntax is for object validation.

I went through the documentation and stack-overflow, but I was not able to find it anywhere online explicitly showing the syntax.

I am sure that I am missing something basic however, being new to this I was hoping that someone can help me.


Solution

  • I understood which you want to validate the testType object. Then there are two ways:

    1. You can add the blackbox: true, this will allow that object have any structure;

    2. You need to define each property of object, like this:

    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,
      },
    };