從集合中的數組中刪除元素時出現錯誤。我正在通過索引刪除元素。當通過索引從數組中刪除元素時出現錯誤「錯誤: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}});
}
});
}
你能證明你的模式文檔的內容在用戶嘗試執行權前更新?特別是my_array的內容。 –
my_array最初是[0]。點擊「添加項目到數組」添加一個新的值,遞增,所以它會變成[0,1,2]等。 –