2015-09-29 15 views
1

從集合中的數組中刪除元素時出現錯誤。我正在通過索引刪除元素。當通過索引從數組中刪除元素時出現錯誤「錯誤:documentMatches需要文檔」

奇怪的是,服務器代碼工作正常,但在控制檯中,我看到一個錯誤「模擬調用'/ patterns/update'的效果時發生異常錯誤:documentMatches需要一個文檔」。

我花了很多年試圖找出問題出在哪裏,我很難過!請參閱下面的代碼以獲取再現問題的最小示例。

(唯一引用我能找到這個錯誤似乎不相關的 - 我覺得這個海報是通過識別不屬性指標元素: Removing an object from an array inside a Collection和這個職位似乎涉及到角度,這我沒有使用。 ,而且這個問題似乎沒有被回答:Minimongo errors when I try to update a document containing an array

任何想法爲什麼查詢可能會在客戶端而不是服務器上失敗?誤差在點發生在我拉元素從數組

Patterns.update({_id: pattern_id}, {$pull : {"my_array" : null}}); 

全碼:

HTML

<head> 
    <title>Array test</title> 
</head> 

<body> 
    {{> hello}} 
</body> 

<template name="hello"> 

    <p>Values in the array: {{array}}</p> 
    <button class="add">Add item to array</button> 
    <button class="remove">Remove item from array</button> 
</template> 

的JavaScript:

Patterns = new Mongo.Collection('patterns'); 
if (Patterns.find().fetch().length == 0) 
{ 
    Patterns.insert({name: "My document", my_array: [0] }); 
} 

if (Meteor.isClient) { 
    Template.hello.helpers({ 
    array: function() { 
     return Patterns.find().fetch()[0].my_array; 
    } 
    }); 

    Template.hello.events({ 
    'click button.add': function() { 
     pattern_id = Patterns.find().fetch()[0]._id; 
     var new_value = Patterns.findOne(pattern_id).my_array.length; 
     Patterns.update({_id: pattern_id}, {$push: {my_array: new_value}}); 
    }, 
    'click button.remove': function() { 
     pattern_id = Patterns.find().fetch()[0]._id; 
     var index = Patterns.findOne(pattern_id).my_array.length -1; 
     var obj = {}; 
     obj["my_array." + index ] = ""; 
     Patterns.update({_id: pattern_id}, {$unset : obj}); 

     // THIS LINE CAUSES THE CONSOLE ERROR 
     Patterns.update({_id: pattern_id}, {$pull : {"my_array" : null}}); 
    } 

    }); 
} 
+0

你能證明你的模式文檔的內容在用戶嘗試執行權前更新?特別是my_array的內容。 –

+0

my_array最初是[0]。點擊「添加項目到數組」添加一個新的值,遞增,所以它會變成[0,1,2]等。 –

回答

3

您正遭遇Minimongo的當前限制,即提到in the source here

// XXX Minimongo.Matcher isn't up for the job, because we need 
    // to permit stuff like {$pull: {a: {$gt: 4}}}.. something 
    // like {$gt: 4} is not normally a complete selector. 
    // same issue as $elemMatch possibly? 

但是,如果您在該異常之後檢查集合,則會看到該項目已從陣列中刪除。這會發生在服務器端(使用真正的MongoDB,然後與您的客戶端集合進行同步),因爲此錯誤僅影響客戶端集合上的客戶端延遲補償操作,然後在更新從服務器。

我的建議給您遇到minimongo限制,將你的更新進入流星方法,你總是在服務器上進行交互的MongoDB,though you will need to add stub methods to handle any latency compensation you require on the client.

+0

謝謝! 在我的項目代碼中,我的更新是流星方法,但它們在客戶端和服務器上運行以啓用樂觀的UI(至少,這是我對它的工作原理的理解,但我對流星還是比較新的)。 也許我可以使用try/catch來防止客戶端顯示錯誤。這樣我仍然在客戶端和服務器上運行相同的功能,並且如果Minimongo更新,它應該可以工作。如果這不起作用,我會按照你的建議分成兩個功能。 –

+0

最後,我將代碼包裝在if(Meteor.isServer){}塊中,以避免由於前一行將元素設置爲null而引起的客戶端錯誤。 (這似乎是通過索引刪除元素的唯一方法,但這是一個兩步過程) –

相關問題