代码之家  ›  专栏  ›  技术社区  ›  Gobliins

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

  •  0
  • Gobliins  · 技术社区  · 7 年前

    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(或default)值获取,如果没有显式设置,则返回foo和bar的值。这可能吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jankapunkt    7 年前

    你可以用 this.field() 方法在你的 autoValue 功能:

    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

    using a hook on the insert method 你的收藏。在那里你可以假设 foo bar 因为您的模式需要它们:

    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
    });
    
    推荐文章