我在事件处理程序中有一个嵌套函数。外部函数从Trees集合创建文档的副本。然后,内部函数从Branches集合创建任何文档的副本,其中id包含在原始树文档的treeBranches
字段中的数组中。
我需要将newTreeId
从外部函数传递给内部函数,以便可以将新的分支ID添加到新文档中的数组中。内部函数中的console.log(newTreeID)
当前返回undefined。
Template.Actions.events({
'change .action-selection': function(e) {
e.preventDefault();
var selection = $(e.target).val();
var currentTreeId = this._id;
var branches = Branches.find({_id:{$in:this.treeBranches}});
switch(selection) {
case "repeat":
return Meteor.call('treeRepeat', currentTreeId, function (newTreeId) {
branches.forEach(function(b) {
var currentBranchId = b._id;
console.log(newTreeId);
Meteor.call('treeBranchesRepeat', currentBranchId, newTreeId, function () {
});
});
});
break;
...
Meteor.methods({
treeRepeat: function(currentTreeId) {
check(currentTreeId, String);
var tree = Trees.findOne({_id:currentTreeId}, {fields:{_id:0, treeBranches:0}});
var newTreeId = Trees.insert(tree);
return {
_id: newTreeId
};
},
treeBranchesRepeat: function(currentBranchId, newTreeId) {
check(currentBranchId, String);
check(newTreeId, String);
var branch = Branches.findOne({_id:currentBranchId}, {fields: {_id: 0}});
var newBranchId = Branches.insert(branch);
Trees.update({_id:newTreeId},{$push:{treeBranches:newBranchId}});
return {
_id: newBranchId
};
}
});
答案 0 :(得分:0)
我认为这可以通过执行树的所有复制并在服务器的单个请求中分支来简化。建议以下工作流程(未测试,但我认为你明白了):
Template.Actions.events({
'change .action-selection': function(e) {
e.preventDefault();
var selection = $(e.target).val();
var currentTreeId = this._id;
var currentTreebranches = this.treeBranches;
switch(selection) {
case "repeat":
return Meteor.call('treeAllRepeat', currentTreeId, currentTreebranches, function (err, res) {
if (err) { console.log(err); }
console.log(res); // Your new tree _id
});
break;
...
Meteor.methods({
treeAllRepeat: function(currentTreeId, branchIds) {
check(currentTreeId, String);
check(branchIds, [String]);
var tree = Trees.findOne({ _id: currentTreeId }, { fields: { _id: 0, treeBranches: 0 } });
if (!tree) {
throw new Error('Tree with id ' + currentTreeId + ' not found');
}
var newTreeId = Trees.insert(tree);
var branches = Branches.find({ _id: { $in: branchIds || [] } });
branches.forEach(function (branch) {
var newBranch = Branches.findOne({ _id: branch._id }, { fields: { _id: 0 } });
var newBranchId = Branches.insert(newBranch);
Trees.update({ _id: newTreeId }, { $push: { treeBranches: newBranchId } });
});
return {
_id: newTreeId
};
}
});
我认为this.treeBranches
是分支的ID?如果没有,你可能想做类似的事情:
var currentTreebranches = _.pluck(this.treeBranches, '_id');
PS。如果您已删除autopublish
包,请记住订阅新树。