Reputation: 5254
I have a Person
and I want a fullName
field and value to automatically be created when a person changes their firstName
or lastName
fields.
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();
}
}
}
}));
If I then do
People.update("ZqvBYDmrkMGgueihX", {$set: {firstName: "Bill"}})
The fullName
is set as Bill undefined
What am I doing wrong?
Upvotes: 0
Views: 222
Reputation: 2677
Right now, your condition firstName.isSet || lastName.isSet
says, if either of firstName
or lastName
is available in the document, then create fullName
. So it is correctly assigning full name, as one of them is set (First Name is set to Bill). You need to use &&
instead of ||
like this.
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();
}
}
}
}));
But, based on your question, I think, you want to set fullName
only when one of firstName
or lastName
is updated then, I think (I am not sure), you need to check this.field('firstName').operator
to check whether it is $set
in the current operation or not.
Upvotes: 1