我想给用户一个按钮,将一个集合中的文档id(以及他们的组名)添加到另一个集合。
我有一个#each循环,它通过模板助手查询返回第一个集合中的每个文档。在每个返回的文档中,我需要检查id是否已添加到另一个集合中,并且根据结果,html中的#if-helper返回不同的输出。
但是"this"返回的是一个空对象,我不知道如何将每个"this"数据上下文传递到"inCollectionTwo"帮助程序中:
<template name="Collections">
{{#each doc in colOne}}
{{#if inCollection2}}
{{> rmvfrmcolTwo doc=doc}}
{{else}}
{{> addtocolTwo doc=doc}}
{{/if}}
{{/each}
</template>
帮助
Template.Collections.helpers({
colOne: function() {
return CollectionOne.find();
},
inCollectionTwo: function(){
var docid = this.colOne._id;
var group = Meteor.user().profile.groupName;
var exists = CollectionTwo.findOne({documentid: docid, groups: { "$in": [group]}});
if(exists) {
return true;
} else {
return false;
}
}
});
由于使用each..in
,因此每次迭代都要将该块的整个数据上下文更改为文档。现在可以在事件处理程序和帮助程序中使用this
关键字引用该文档。
{{#each doc in colOne}}
{{#if inCollectionTwo)}}
{{> rmvfrmcolTwo doc=doc}}
{{else}}
{{> addtocolTwo doc=doc}}
{{/if}}
{{/each}}
在你的助手:
Template.Collections.helpers({
//...
inCollectionTwo: function() {
// `this` is the `doc` from the #each block in your template
var docid = this._id;
//...
}
}
编辑:或者,您可以将新上下文作为参数传递给助手
{{#each doc in colOne}}
{{#if (inCollectionTwo doc)}}
...
在你的助手中
inCollectionTwo: function( doc ) {
var docid = doc._id;
//...
}
Meteor Guide在这里有一个关于Blaze和each..in
循环的详细章节。你可以用其他一些方法来解释你的问题,但这应该让你开始。