javascriptnode.jsmeteorsimple-schemameteor-collection2

Meteor Collections Simpleschema, autovalue depending on other field values


i have three fields in a Collection:

Cards.attachSchema(new SimpleSchema({
  foo: {
    type: String,
  },
  bar: { 
    type: String,
  },
  foobar: {
    type: String,
    optional: true,
    autoValue() { 
      if (this.isInsert && !this.isSet) {
        return `${foo}-${bar}`;
      }
    },
  },
);

So i want to have the field foobar to get as auto(or default) value, if not explicitly set, to return both values of foo and bar. Is this possible?


Solution

  • You may use the this.field() method inside your autoValue function:

    Cards.attachSchema(new SimpleSchema({
      foo: {
        type: String,
      },
      bar: { 
        type: String,
      },
      foobar: {
        type: String,
        optional: true,
        autoValue() { 
          if (this.isInsert && !this.isSet) {
            const foo = this.field('foo') // returns an obj
            const bar = this.field('bar') // returns an obj
            if (foo && foo.value && bar && bar.value) {
              return `${foo.value}-${bar.value}`;
            } else {
              this.unset()
            }
          }
        },
      },
    );
    

    Related reading: https://github.com/aldeed/simple-schema-js#autovalue

    However, you could also solve this by using a hook on the insert method of your collection. There you could assume the values foo and bar to be present, because your schema requires them:

    Cards.attachSchema(new SimpleSchema({
      foo: {
        type: String,
      },
      bar: { 
        type: String,
      },
      foobar: {
        type: String,
        optional: true,
      },
    );
    
    
    
    Cards.after.insert(function (userId, doc) {
       // update the foobar field depending on the doc's 
       // foobar values
    });