meteormeteor-autoformsimple-schemameteor-collection2

SimpleSchema invalid keys "_id required"


I'm using aldeed:autoform, aldeed:simple-schema, aldeed:collection2 and mdg:validated-method for doing an insert over a collection.

This is the tempalte with the AutoForm:

<template name="Areas_agregar">
  {{> Titulos_modulos title="Areas" subtitle="Agregar" cerrar=true}} 
  {{ 
    #autoForm 
    collection=areasColecction 
    id="areas_agregar" 
    type="method" 
    meteormethod="areas.insert" 
  }} 
  {{> afQuickField name='nombre'}} 
  {{> afArrayField name='subareas'}}

  <button type="submit">Save</button>

  <button type="reset">Reset Form</button>
  {{/autoForm}}
</template>

This is the collection's schema:

Areas.schema = new SimpleSchema({
    _id: { 
        type: String, 
        regEx: SimpleSchema.RegEx.Id 
    },
    nombre: { 
        type: String,
        label: 'Nombre'
    },
    subareas: {
        type: [String],
        label: 'Subareas'
    }
});

And this is the insert method:

const AREA_FIELDS_ONLY = Areas.simpleSchema().pick(['nombre', 'subareas', 'subareas.$']).validator({ clean: true, filter: false });

export const insert = new ValidatedMethod({
    name: 'areas.insert',
    validate: AREA_FIELDS_ONLY,
    run({ nombre, subareas }) {
        const area = {
            nombre, 
            subareas
        };
        Areas.insert(area);
    },
});

And i'm getting the folowing error in Chrome's Dev Console:

SimpleSchema invalid keys for "areas_agregar" context: Array[1] 0: Object name: "_id" type: "required" value: null proto: Object length: 1 proto: Array[0]

Like the error shows, is asking me a value for the _id field, but I'm on an insert update, it doesn't makes any sense.

Any idea what could be going wrong?


Solution

  • autoform treats required keys in the schema as being required in the form input which doesn't work for the _id key.

    If you make the _id optional: true then your insert will work and Meteor will automatically insert the _id OR you can use a variation of the schema for the autoform which omits the _id key altogether:

    let schemaObject = {
      nombre: { 
        type: String,
        label: 'Nombre'
      },
      subareas: {
        type: [String],
        label: 'Subareas'
      }
    };
    Areas.formSchema = new SimpleSchema(schemaObject); // use for form
    schemaObject._id = { 
      type: String, 
      regEx: SimpleSchema.RegEx.Id 
    };
    Areas.collectionSchema = new SimpleSchema(schemaObject); // use for collection