meteorsimple-schemameteor-collection2

Schema error when reusing same field


I have two separate schemas that use the same field. I've tried to create schemaComponents so that I can update both schemas in one location however I get an error Error: Invalid definition for school.$ field. when I use it. I'm not sure what I'm doing wrong here, I was under the impression this was allowed.

Path: SchemaComponents.js

SchemaComponents = {
  schools: {
    type: [String],
    optional: true,
    autoform: {
      options: [
        {label: "School One", value: 'SchoolOne'},
        {label: "School Two", value: 'SchoolTwo'},
        {label: "School Three", value: 'SchoolThree'},
      ]
    }
  }
};

Path: StudentSchema.js

import from '../components/SchemaComponents.js';
StudentSchema = new Mongo.Collection("studentSchema");

var Schemas = {};

Schemas.StudentSchema = new SimpleSchema({
    school: SchemaComponents.schools,
});

StudentSchema.attachSchema(Schemas.StudentSchema);

Path: TeacherSchema.js

import from '../components/SchemaComponents.js';
TeacherSchema = new Mongo.Collection("teacherSchema");

var Schemas = {};

Schemas.TeacherSchema = new SimpleSchema({
    school: SchemaComponents.schools,
});

TeacherSchema.attachSchema(Schemas.TeacherSchema);

Solution

  • You defined SchemaComponent as a simple object and not as a SimpleSchema object. To reuse your schools definition do:

    let schoolsSchema = new SimpleSchema({
      schools: {
        type: [String],
        optional: true,
        autoform: {
          options: [
            {label: "School One", value: 'SchoolOne'},
            {label: "School Two", value: 'SchoolTwo'},
            {label: "School Three", value: 'SchoolThree'},
          ]
        }
      }
    });
    

    Then you can do:

    Schemas.TeacherSchema = new SimpleSchema({
      school: {
        type: schoolsSchema
      }
    });