Meteor Autoform`his.field(“keyName”)。value`在Schema中返回undefined

时间:2016-03-14 06:08:32

标签: meteor meteor-autoform meteor-collection2 simple-schema

我有一个Person,我希望当一个人更改fullNamefirstName字段时自动创建lastName字段和值。

People.attachSchema(new SimpleSchema({
    firstName: {
        type: String,
        optional: false,
        label: 'First Name'
    },
    lastName: {
        type: String,
        optional: false,
        label: 'Last Name'
    },
    fullName: {
        type: String,
        optional: false,
        label: 'Full Name',
        autoValue: function() {
          var firstName = this.field("firstName");
          var lastName = this.field("lastName");

          if(firstName.isSet || lastName.isSet){
                return firstName.value + " " + lastName.value;
            } else {
                this.unset();
            }
          }
    }
}));

如果我那么做

People.update("ZqvBYDmrkMGgueihX", {$set: {firstName: "Bill"}})

fullName设为Bill undefined

我做错了什么?

1 个答案:

答案 0 :(得分:1)

目前,您的条件firstName.isSet || lastName.isSet表示,如果文档中有firstNamelastName,则创建fullName。所以它正确分配全名,因为其中一个已设置(名字设置为Bill)。您需要使用&&代替此||

People.attachSchema(new SimpleSchema({
    firstName: {
        type: String,
        optional: false,
        label: 'First Name'
    },
    lastName: {
        type: String,
        optional: false,
        label: 'Last Name'
    },
    fullName: {
        type: String,
        optional: false,
        label: 'Full Name',
        autoValue: function() {
            var firstName = this.field("firstName");
            var lastName = this.field("lastName");

            if(firstName.isSet && lastName.isSet){
                return firstName.value + " " + lastName.value;
            } else {
                this.unset();
            }
        }
    }
}));

但是,根据您的问题,我认为,您只想在fullNamefirstName中的某个更新时设置lastName,我认为(我不确定),您需要检查this.field('firstName').operator以检查当前操作中是否$set