0

I'd like to build an up a 'topic' object in my Meteor app's User.profile property. Here is what I have so far:

Template.addToReviewList.events({
  'submit form': function(theEvent) {
    theEvent.preventDefault();
    var selectedTopic = Session.get('selectedTopic');
    Meteor.users.update({_id:Meteor.user()._id}, {$set: {'profile.topics': selectedTopic}});
  }
});

This works as expected creating something like User.profile.topics: math. If I select a new topic and run it again my topic gets updated accordingly. Again this is expected.

I'd like to build a 'topic' object so that each time the function runs, it results in something like this:

User.profile.topics: { topic1: true, topic2: true, topic3: true,...}

I've tired every combination of string concating the User.profile.topics I can think of and none of them work. Here is one example:

Template.addToReviewList.events({
  'submit form': function(theEvent) {
    theEvent.preventDefault();
    var selectedTopic = Session.get('selectedTopic');
    Meteor.users.update({_id:Meteor.user()._id}, {$set: {'profile.topics.'+selectedTopic: true}});
  }
});

Am I not escaping something properly? Do I need to use a different Mongo Field operator? Something else?

Thanks in advance.

Chris
  • 115
  • 9
  • Have a look at this answer : http://stackoverflow.com/questions/25656151/how-to-replace-the-key-for-sort-field-in-a-meteor-collection-query I think this is the same problem. – saimeunt Sep 04 '14 at 18:47
  • 1
    Or [this one](http://stackoverflow.com/questions/21503342/numeric-field-names-in-meteor-collection), or [this one](http://stackoverflow.com/questions/22315877/mongo-sort-by-dynamic-field), or [this one](http://stackoverflow.com/questions/22568673/updating-a-specific-element-in-an-array-with-mongodb-meteor). :) It's probably the single most common pitfall that people encounter but it's really hard to search for. BTW you can just do `Meteor.users.update(Meteor.userId(), {$set: ...)`. – David Weldon Sep 04 '14 at 19:05

1 Answers1

0

If you want to create dynamic keys in object you cannot do that using object literal. Instead you need to dynamically add keys to object using this approach;

var setobject = {};
setObject['profile.topics.'+selectedTopic] = true;
Meteor.users.update({_id:Meteor.user()._id}, {$set:setObject});
Kuba Wyrobek
  • 5,273
  • 1
  • 24
  • 26
  • This worked, thanks a ton! Is this a javascript, meteor or mongo convention? – Chris Sep 04 '14 at 19:54
  • That is javascript. Play with JS in console and you will see that doing dynamic keys (`'profile.topics.'+selectedTopic`) with object literal is not possible. – Kuba Wyrobek Sep 04 '14 at 20:05