Javascript 使用集合挂钩将新文档的id添加到现有文档的数组中
我使用了Javascript 使用集合挂钩将新文档的id添加到现有文档的数组中,javascript,meteor,hook,meteor-collection-hooks,Javascript,Meteor,Hook,Meteor Collection Hooks,我使用了matb33:collection hooks在插入一个文档后插入另一个文档,是否可以在插入后更新现有文档?我正在努力做到以下几点: 在其数据上下文具有boxId的\u id的模板框中,调用方法将新文档插入到目标集合中 获取新文档的\u id,并将其添加到具有boxId的\u id的文档数组中 由于this引用了钩子中的新文档,因此我不知道如何获取boxId来更新正确的文档 根据Pawel的回答,此处为最终代码: Template.Box.events({ 'click .a
matb33:collection hooks
在插入一个文档后插入另一个文档,是否可以在插入后更新现有文档?我正在努力做到以下几点:
- 在其数据上下文具有
的boxId
的模板\u id
框中,调用方法将新文档插入到
集合中目标
- 获取新文档的
,并将其添加到具有\u id
的boxId
的文档数组中\u id
this
引用了钩子中的新文档,因此我不知道如何获取boxId
来更新正确的文档
根据Pawel的回答,此处为最终代码:
Template.Box.events({
'click .add button': function(e) {
e.preventDefault();
var currentBoxId = this._id;
var target = {
...
};
Meteor.call('targetAdd', target, currentBoxId, function(){});
}
});
Meteor.methods({
targetAdd: function(targetAttributes, currentBoxId) {
check(this.userId, String);
check(currentBoxId, String);
check(targetAttributes, {
...
});
var target = _.extend(targetAttributes, {
userId: user._id,
submitted: new Date()
});
var targetId = Targets.insert(target);
Boxes.update(currentBoxId, {$addToSet: {targets:targetId}});
return {
_id: targetId
};
}
});
收集钩子不知道文档插入/更新的位置,也不依赖于文档插入/更新的位置(这是收集钩子的一个要点——不管操作来自何处,钩子的行为应该始终相同) 更重要的是,即使您的targetAdd方法也没有boxId,您必须将其作为参数之一传递 因此,在本例中,您应该将boxId作为参数传递给targetAddMethod,并在该方法中修改box文档
仅在收集操作的上下文不重要的情况下使用收集挂钩。您只需将boxId传递给方法,然后传递给新记录,它将出现在挂钩中:
Template.Box.events({
'click .add button': function(e) {
e.preventDefault();
var target = {
...
};
Meteor.call('targetAdd', target, this._id, function(){});
}
});
Meteor.methods({
targetAdd: function(targetAttributes, boxId) {
check(this.userId, String);
check(boxId, String);
check(targetAttributes, {
...
});
var target = _.extend(targetAttributes, {
submitted: new Date(),
boxId: boxId
});
var targetId = Targets.insert(target);
return {
_id: targetId
};
}
});
Targets.after.insert(function () {
var targetId = this._id;
var boxId = this.boxId;
Boxes.update({_id:boxId}, {$addToSet: {targets: targetId}}, function () {
});
});
boxId从哪里来?我只在
after
hook中看到它,其中该值也可用?boxId是触发Targets.insert的模板中数据上下文的_id。但是我应该在哪里找到钩子呢?我可以在钩子中定义它吗(我在哪里有?我尝试了Template.parentData,但返回的是未定义的。或者我需要从前面的一点传递它吗?你会编辑你的问题吗?所以我不应该在这里使用钩子,而是应该在同一个方法中执行Targets.insert和box.update?是的,你应该这样做。谢谢,这很有效,我更新了代码以显示已解析的答案。但不应将boxId添加到新的目标记录中。它只能用于通过向数组添加新的TargetId来查找要更新的现有Box文档。我在其他地方有一个用例,它允许目标文档被其他Box模板使用。我可以在不添加到新文档的情况下通过该方法传递boxId吗?可以,但在insert hook中不可用