簡體   English   中英

流星集合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字段作為auto(或默認)值(如果未顯式設置)以返回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

但是,您也可以通過集合insert方法上使用鈎子來解決此問題。 在那里,您可以假定存在值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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM