Meteor Collections Simpleschema,自动值取决于其他字段值

Meteor Collections Simpleschema, autovalue depending on other field values

我在一个集合中有三个字段:

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

所以我想让字段 foobar 获得自动(或默认)值,如果没有明确设置,return foo 和 bar 的两个值。这可能吗?

您可以在 autoValue 函数中使用 this.field() 方法:

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

相关阅读:https://github.com/aldeed/simple-schema-js#autovalue

不过,您也可以通过 collection 的 using a hook on the insert method 来解决这个问题。在那里你可以假定值 foobar 存在,因为你的架构需要它们:

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