So I have the following form:
template(name='editUser')
.row
.col-md-4.col-md-offset-4
.page-header
h1 Edit user
form#edit-user-form
.form-group
label(for='name') Name
input#user-name.form-control(type='text' placeholder='Name' value='{{user.name}}')
.form-group
label(for='email') E-Mail
input#user-email.form-control(type='text' placeholder='E-Mail' value='{{getEmail user}}')
button.btn.btn-primary(type='submit') Update
the following handlebars.js-Helper:
Handlebars.registerHelper('getEmail', function (user) {
if (user.emails && user.emails[0] && user.emails[0].address)
return user.emails[0].address;
return '';
});
and the following iron-Router code:
EditUserController = RouteController.extend({
template: 'editUser',
waitOn: function () {
return Meteor.subscribe('user', this.params._id);
},
data: function () {
return {
user: Meteor.users.findOne( { _id: this.params._id } )
};
}
});
If I run my application and click on the link to the edit-User-Form I can see the E-Mail Address. But if I change my code and Meteor automatically refreshes the page, the E-Mail-Field is empty and the console says, that it can't fetch the value of undefined.
If I use the same form, but with a with-Helper, the E-Mail is displayed even if Meteor automatically refreshes the page:
template(name='editUser')
.row
.col-md-4.col-md-offset-4
.page-header
h1 Edit user
form#edit-user-form
with user
.form-group
label(for='name') Name
input#user-name.form-control(type='text' placeholder='Name' value='{{name}}')
.form-group
label(for='email') E-Mail
input#user-email.form-control(type='text' placeholder='E-Mail' value='{{getEmail this}}')
button.btn.btn-primary(type='submit') Update
Why is this so? And should I always use the with-Helper if I get single Results (only one Result to display)?
Thanks in advance!
Replace Meteor.users.findOne
with Meteor.users.find
.
When findOne
doesn’t find anything, it returns undefined
which causes your error; when find
doesn’t find anything, it returns an empty cursor which Meteor knows what to do with. Essentially all you were doing by adding with
was to cause Meteor to check if the value was undefined, but that check isn’t necessary for a cursor, empty or otherwise.