[英]How can I sort a cursor using ids from another document array?
當我對#each
迭代中顯示的項目進行排序時,我想更新SpaceBars @index
本機幫助程序。 我猜想正確的方法是對#each
使用的游標進行排序。
光標來自Items
集合。 我用來對它們進行排序的數組屬於另一個收集文檔( Projects
),並且它存儲每個已發布項目ID的有序列表。
將項目放到新位置后,我使用可排序stop
功能更新項目文檔數組中的每個項目索引。 要做到這一點,我$pull
出來,然后再$push
在特定的位置吧。
stop: function(e, ui) {
var project = Projects.findOne();
// get the dragged html element and the one before and after it
el = ui.item.get(0)
before = ui.item.prev().get(0)
after = ui.item.next().get(0)
console.log(Blaze.getData(el)._id); //gets the id of the item dropped
if(!before) {
//if it was dragged into the first position
console.log(after.dataset.index); //gets the index of the next element
Projects.update({_id: project._id},
{$pull:
{
items:Blaze.getData(el)._id
}
})
Projects.update({_id: project._id},
{$push:
{
items:
{
$each:[Blaze.getData(el)._id],
$position:0
}
}
})
} else if(!after) {
//if it was dragged into the last position
Projects.update({_id: project._id},
{$pull:
{
items:Blaze.getData(el)._id
}
})
Projects.update({_id: project._id},
{$push:
{
items: Blaze.getData(el)._id
}
})
} else
Projects.update({_id: project._id},
{$pull:
{
items:Blaze.getData(el)._id
}
})
Projects.update({_id: project._id},
{$push:
{
items:
{
$each:[Blaze.getData(el)._id],
$position:after.dataset.index -1
}
}
})
}
如您所見,我在上面的函數中使用了項目的index屬性(例如$position:after.dataset.index -1
)。 這是我要通過對光標進行排序來更新的內容。
概括起來,一方面,我有一個有序的(使用索引)ID數組; 例:
items : {
Id2131,
Id4233,
Id2243,
Id2331,
Id2455,
Id2123
}
另一方面,我有一個出版物,其中所有ID都與數組匹配,但順序不正確。
如何按照其他文檔數組的順序對游標Items.find()
進行排序?
我才意識到該怎么做。 這是我繼續的方法。
提供#each
迭代的幫助程序不再返回簡單的Items.find()
,而是使用專用功能對其進行排序的數組版本。 現在返回sortItems(Items.find())
並且sortItems
函數看起來像這樣:
var sortItems= function(cursor) {
if(!cursor) {
return [];
}
var raw = cursor.fetch();
var project = Projects.findOne()
var sorted = [];
_.each( project.items, function(id){
_.each( raw, function(item){
if (item._id === id) {
sorted.push(item);
}
})
})
return sorted;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.