Uniforms: [QUESTION] foreign key in uniforms

Created on 9 Jun 2020  路  3Comments  路  Source: vazco/uniforms

Hi, does Uniforms support having foreign keys?
Im using simpl-schema.
Let say I have

export const CountrySchemaDefinition = {
    _id: {
        type: String,
        regEx: SimpleSchema.RegEx.Id,
        uniforms: {
            component: () => null,
        },
    },
    name: {
        type: String,
        min: 2,
    },
};

export const StudentSchemaDefinition = {
    _id: {
        type: String,
        regEx: SimpleSchema.RegEx.Id,
        uniforms: {
            component: () => null, 
        },
    },
    lastName: {
        type: String,
        min: 2,
    },
    country: {
        allowedValues: () => Country.find().fetch().map(p => p.name),
        type: String,
    },
};

This works by showing the country names when I create/edit/list with AutoForm. But it stores the country.name, not country.id in the mongo DB
Is there a way to show the country.name in AutoForm but store the country._id in the DB?
I was thinking in creating a component/field for that, but may be there are better ways, or out of the box solutions.

question

All 3 comments

Uh, seems I found a solution using transforms:

export const StudentSchemaDefinition = {
    _id: {
        type: String,
        regEx: SimpleSchema.RegEx.Id,
        uniforms: {
            component: () => null, 
        },
    },
    lastName: {
        type: String,
        min: 2,
    },
    country: {
        allowedValues: () => Country.find().fetch().map(p => p._id),
        uniforms: {
            transform: id => Country.findOne({ _id:  id }).nombre,
        },
        type: String,
    },
};

Hi @rafahoro. I'm glad you've found the solution by yourself!

Found another (simpler) way of solving this
Instead of allowedValues + transform

 country: {
        allowedValues: () => Country.find().fetch().map(p => p._id),
        uniforms: {
            transform: id => Country.findOne({ _id:  id }).nombre,
        },
        type: String,
    },

just use options

 country: {
      uniforms: {
          options: () => Country.find().fetch().map(p => ({ label: p.nombre, value: p._id })),),
      },
      type: String,
  },
Was this page helpful?
0 / 5 - 0 ratings