Search code examples
meteormeteor-collection2simple-schema

How to create reusable component with simpleSchema


I might be thinking about this the wrong way, so please feel free to correct my thinking.

I'm using simpleSchema and I have a section of code which is used in more than one schema. Is there a way to create an individual component and import it into each schema, so that when I need to update the component I don't have to update it in multiple locations?

Path: resuableComponent

type: String,
  optional: true,
  autoform: {
    type: "select",
    options: function () {
      return [
        {label: "School logo 1", value: 'url'},
        {label: "School logo 2", value: 'url'},
        {label: "School logo 3", value: 'url'},
      ];
    },
  }

Path: studentCollection.js

Schemas.Student = new SimpleSchema({
    studentUserId: {
        type: String,
    },
    school: {
        type: String,
        optional: false
    },
    **resuableComponent**
});

Path: teacherCollection.js

Schemas.Teacher = new SimpleSchema({
    teacherUserId: {
        type: String,
    },
    school: {
        type: String,
        optional: false
    },
    **resuableComponent**
});

Solution

  • You could move the reusable objects into a different file that should be visible on both client and server if you are using SimpleSchema.

    Example based on your question:

    lib/schema-components.js :

    SchemaComponents = {
      school: {
        type: String,
        optional: false
      },
      // ...
      // more reusable components here
    };
    

    someCollectionFile.js :

    Schemas.Student = new SimpleSchema({
        studentUserId: {
            type: String
        },
        school: SchemaComponents.school,
        // ...
    });