使用集合钩子将新文档的 id 添加到现有文档中的数组中

Add id of new document to array in existing document using collection-hooks

本文关键字:文档 添加 id 数组 集合 新文档      更新时间:2023-09-26

我用matb33:collection-hooks插入到另一个文档后插入文档,是否可以在插入后更新现有文档? 我正在尝试执行以下操作:

  • 在数据上下文具有boxId _id的模板Box中,调用将新文档插入Targets集合的方法
  • 获取新文档的_id,并将其添加到_idboxId 的文档数组中。

由于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 作为参数传递给 targetAdd 方法并修改该方法中的框文档。

仅当收集操作的上下文不重要时,才使用集合挂钩。

你可以将 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 () {
    }); 
});