Wulf Wulf - 1 year ago 93
Javascript Question

Limiting fields returned by mongo dynamically

I use Meteor to query a mongo collection. It has for example the following entry:

"_id": "uCfwxKXyZygcWQeiS",
"gameType": "foobar",
"state": "starting",
"hidden": {
"correctAnswer": "secret",
"someOtherStuff": "foobar"
"personal": {
"Y73uBhuDq2Bhk4d8W": {
"givenAnswer": "another secret",
"hQphob8s92gbEMXbY": {
"givenAnswer": "i have no clue"

What I am trying to do now is:

  • don't return the values behind "hidden"

  • from the "personal" embedded document only return the values for the asking user

In code it would look something like this:

Meteor.publish('game', function() {
this.related(function(user) {
var fields = {};
fields.hidden = 0;
fields.personal = 0;
fields['personal.' + this.userId] = 1;

return Games.find({}, {fields: fields});

}, Meteor.users.find(this.userId, {fields: {'profile.gameId': 1}}));

Obviously this won't work, because MongoDB won't allow mixed includes and excludes. On the other hand, I cannot switch to "specify only the included fields", because they can vary from gameType to gameType and it would become a large list.

I really hope that you can help me out of this. What can I do to solve the problem?

Answer Source

Typical example of where to use the directly controlled publication features (the this.added/removed/changed methods). See the second example block a bit down the page at http://docs.meteor.com/api/pubsub.html#Meteor-publish.

With this pattern you get complete control of when and what to publish.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download