0

我有一个Person并且我希望在一个人更改其或字段fullName时自动创建一个字段和值。firstNamelastName

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

我究竟做错了什么?

4

1 回答 1

1

现在,您的条件firstName.isSet || lastName.isSet是,如果文档中有一个firstNamelastName可用,则创建fullName. 所以它正确地分配了全名,因为其中一个已设置(名字设置为比尔)。你需要使用&&而不是||这样。

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

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

于 2016-03-14T08:54:32.160 回答