我有一个Person
,我希望当一个人更改fullName
或firstName
字段时自动创建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
我做错了什么?
答案 0 :(得分:1)
目前,您的条件firstName.isSet || lastName.isSet
表示,如果文档中有firstName
或lastName
,则创建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();
}
}
}
}));
但是,根据您的问题,我认为,您只想在fullName
或firstName
中的某个更新时设置lastName
,我认为(我不确定),您需要检查this.field('firstName').operator
以检查当前操作中是否$set
。