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

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

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

由于 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
        };
    }
});

收集挂钩不知道也不依赖于文档的位置 inserted/updated(这是收集挂钩的要点之一 - 操作来自何处并不重要,钩子应该始终以相同的方式运行)。

此外,即使您的 targetAdd 方法还没有 boxId - 您必须将其作为参数之一传递。

所以在这种情况下,您应该将boxId作为参数传递给targetAdd方法,并在方法中修改box文档。

仅在收集操作的上下文不重要的情况下使用收集挂钩。

你可以直接将boxId传递给方法,然后传递给新的记录,它会出现在hook中:

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 () {
    }); 
});