Простая схема Meteor Collections, автоматическое значение в зависимости от значений других полей

у меня есть три поля в коллекции:

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. Это возможно?


person Gobliins    schedule 24.10.2018    source источник


Ответы (1)


Вы можете использовать метод 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

Однако вы также можете решить эту проблему, используя хук в методе insert вашей коллекции. Там вы можете предположить, что значения 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
});
person Jankapunkt    schedule 25.10.2018
comment
Спасибо, я попробую как можно скорее - person Gobliins; 30.10.2018