Reputation: 1003
I've got a findOne()
in a template helper in Meteor but I want to modify an array in the document before returning both the document as well as the updated array. When doing so I get TypeError: Cannot read property 'access' of undefined
. On the initial test it worked fine but I suspect that it's now failing because I'm trying to modify the document before findOne()
completes. How do I get around this? Code below:
'curMatter': function() {
var curObj = Matters.findOne({_id:Session.get('editing_matter')});
var curAccess = _.without(curObj.access, Meteor.userId());
return { curMatter: curMatter, curAccess: curAccess };
}
Upvotes: 0
Views: 69
Reputation: 11197
just use it as a cursor, they always seem to work better anyway.
Template['someTemplate'].helpers({
curMatter: function () {
return Matters.find({
_id: Session.get('editing_matter')
}).map(doc => Object.assign(doc, {
curAccess: _.without(doc.access, Meteor.userId())
}))
}
});
Then you can use an {{#each}}
in your template (even if it is always one item)
Upvotes: 0
Reputation: 317
Collection.findOne
completes before running code code that is after it (var curAccess = _.without(curObj.access, Meteor.userId());
in your case).
The issue is that the document that you expect to get by this query is not available (yet) to the client, so Matters.findOne({_id:Session.get('editing_matter')});
returns undefined
.
So what it really means that your subscription is not ready, when the helper is run for the first time, and it fails.
What you can do is to check whether curObj
is not undefined
before accessing its property (i.e. var curAccess = curObj && _.without(curObj.access, Meteor.userId());
When the document becomes available to the client, the helper will be re-run, and you will get correct results then.
Here is your complete code:
'curMatter': function() {
var curObj = Matters.findOne({_id:Session.get('editing_matter')});
var curAccess = curObj && _.without(curObj.access, Meteor.userId());
return { curMatter: curMatter, curAccess: curAccess };
}
Upvotes: 1