I want to add some dynamically computed properties to a server side collection and then send this combined collection to the client.
Lets say I have a simple page where one could post questions and then attach answers to those.
There are two collections: Questions
and Answers
.
Each answer has a property questionId
.
On the client side I would like to show a list of all questions, each with it's answer count. I don't want to send the Answers
collection down the wire due to bandwidth considerations. Ideally I want the count to behave reactively.
- Question 1 (12 Answers)
- Question 2 (4 Answers)
My Solutions for this so far don't look very 'Meteorish' to me.
First Solution was to simply add an answerCount
property to each question and then modify that property when an answer was added or deleted. However I don't like the duplicated information and it also does not work if the computation has some dynamic parameters that might change.
Second Solution was to use a method call for the server side computation:
Meteor.methods({
numOfAnswers: function(questionId) {
return Answers.find({questionId: questionId}).count();
}
});
From the client side I would use a template helper like:
numOfAnswers: function(){
return ReactiveMethod.call("numOfAnswers", this._id);
}
Even though this works fine, it causes a lot of method calls and it is not reactive at all.
Probably another solution could be to use MongoDB aggregations (maybe via meteorhacks:aggregate) but then again this is not reactive and maybe a bit overkill.
I ran into this problem a few times at different places. Do I miss something obvious here?