2014-09-04 89 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

相關問題