简体   繁体   中英

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?

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM