Jamgreen Jamgreen - 7 months ago 37
Javascript Question

Transform fields before publishing to client in Meteor

I have a quiz app in Meteor.

I have fields

correctAnswers
and
wrongAnswers
.

Is it possible to publish correct answers and wrong answers in a shuffled array to the client?

Right now, the user can just open his console and type
Questions.find().fetch()
and see the correct answers.

An alternative would of course be to store all answers (both wrong and correct) in an array and keep the index of correct answers in another field, which is not populated to the client, but I rather want a more intuitive data structure.

Answer

You can create two publications on the same collection: one which only publishes the questions without answers and another that publishes the answers to already answered questions. Meteor will union these data on the client so that you can query the collection consistently but essentially you have to defer the pushing of the answers to the client.

Meteor.publish('questionsOnly',function(){
  return Questions.find({},{fields: {questionText: 1}});
});

Meteor.publish('answersOnly',function(answeredQuestions){
  return Questions.find({_id: {$in: answeredQuestions}},{fields: {correctAnswers: 1, wrongAnswers: 1}});
});