2014-09-04 91 views
0

我想在我的Meteor应用程序的User.profile属性中构建一个'主题'对象。这是我到目前为止:如何将user.profile属性设置为Meteor中的变量名称?

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}}); 
    } 
}); 

这符合预期创建User.profile.topics类似的东西:数学。如果我选择一个新主题并再次运行,我的主题会相应更新。这也是预料之中的。

我想建立一个“主题”对象,每个函数运行时间,它会导致这样的事情:

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

我已经厌倦了concating的User.profile字符串的每个组合。我能想到的话题并没有一个能起作用。这里有一个例子:

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}}); 
    } 
}); 

我是不是没有正确地逃避什么?我需要使用不同的Mongo Field操作员吗?还有别的吗?

在此先感谢。

+0

看看这个答案:http://stackoverflow.com/questions/25656151/how-to-replace-the-key-for-sort-field-in-a-meteor-collection-query我认为这是同样的问题。 – saimeunt 2014-09-04 18:47:21

+1

或[this one](http://stackoverflow.com/questions/21503342/numeric-field-names-in-meteor-collection)或[this one](http://stackoverflow.com/questions/22315877/ mongo-sort-by-dynamic-field)或[this one](http://stackoverflow.com/questions/22568673/updating-a-specific-element-in-an-array-with-mongodb-meteor)。 :)这可能是人们遇到的唯一最常见的陷阱,但它很难搜索。顺便说一句,你可以做'Meteor.users.update(Meteor.userId(),{$ set:...)'。 – 2014-09-04 19:05:14

回答

0

如果要在对象中创建动态键,则不能使用对象字面值来实现。相反,您需要使用此方法动态地将键添加到对象;

var setobject = {}; 
setObject['profile.topics.'+selectedTopic] = true; 
Meteor.users.update({_id:Meteor.user()._id}, {$set:setObject}); 
+0

这工作,谢谢一吨!这是一个JavaScript,流星或mongo公约? – Chris 2014-09-04 19:54:44

+0

这就是javascript。在控制台中玩JS,你会发现用对象字面值做动态键(''profile.topics。'+ selectedTopic')是不可能的。 – 2014-09-04 20:05:31

相关问题