2016-02-12 46 views
0

我是JavaScript新手,對流星很新。這段代碼是否正確?我需要定義一個函數,它將採用一組值並將它們插入Meteor集合「FooterButtons」中?在JavaScript數組中應用Meteor集合插入循環

客戶端代碼

replaceCollectionContents(['NO', 'B', 'YES']); 

兩個代碼

replaceCollectionContents = function (buttonsList) { 
    FooterButtons.remove(); 
    for(i = 0; i < buttonsList.length; i++) { 
    FooterButtons.insert(buttonsList[i]); 
    } 
}; 
+0

護理髮表評論,以什麼起色,你可以做寫這個問題,以便其他可能學習如何避免寫一個附帶向下投票的問題? :) –

+0

http://stackoverflow.com/help/mcve。你有什麼具體的嘗試,你看到什麼特定的錯誤,等等。 – Quotidian

回答

1

您不能直接插入一個字符串的集合。 insert方法需要一個類型爲object的文檔。

試試這個 -

FooterButtons.insert({ text: buttonsList[i] }); 

另外,我注意到你正在試圖清除您的收藏FooterButtons。請注意,您不能從客戶端清除這樣的集合,因爲它被認爲是不可信的代碼。從客戶端,您一次只能刪除一個文件,由其_id指定。

我建議你改用一種方法。

Meteor.methods({ 
    replaceCollectionContents: function (buttonsList) { 
    // remove all existing documents in the collection 
    FooterButtons.remove({}); 

    // insert new button documents into the collection 
    buttonsList.forEach(function (button) { 
     FooterButtons.insert({ text: button }); 
    }); 
    } 
}); 

,需要

Meteor.call("replaceCollectionContents", ['NO', 'B', 'YES']); 

裏面的方法時,調用此方法,請注意,我傳遞一個{}選擇到remove方法,因爲出於安全原因,流星不一樣,如果選擇刪除任何文件被省略。

您可以在Meteor文檔中閱讀更多關於remove的文章。

+0

我得到一個錯誤「這個JavaScript版本不支持」,我的流星安裝有[email protected]和[email protected]。你的代碼是用ECMAScript 6編寫的嗎? –

+0

是的,我已經使用了一些ES6來進行方法聲明。我編輯了答案。這應該防止錯誤。 – umesh

1

如果我理解正確,則需要將種子數據輸入FooterButtons集合,對嗎?

將這個代碼某處你server文件夾:

buttonsList = ['NO', 'B', 'YES']; 

if (FooterButtons.find().count() === 0) { 
    _.each(buttonsList, function(button) { 
    FooterButtons.insert({text: button}); 
    }); 
} 

運行流星,並檢查您的MongoDB FooterButtons集合。讓我知道。我會解釋,如果這項工作

如果需要更新,那麼更新:

FooterButtons.update({text:'B'}, {$set:{text:'Extra'}}); 
+0

是的。但是,如果我更改數組中其中一個項目的文本(將B指定爲Extra),模板將不會顯示新文本 –

+0

我編輯我的答案 – asingh