我正在使用嵌套函数调用两个方法来复制一组文档。这些文档来自两个不同的集合,但是由treeBranches字段链接,如下所示。
树木收藏
{
_id: "tree_1",
treeBranches: ["branch_1","branch_2"],
...
}
分支集合
{
_id: "branch_1",
branchName: "Branch 1",
...
}
{
_id: "branch_2",
branchName: "Branch 2",
...
}
我不明白如何在_id
中获取每个现有分支文档的branches.forEach
。现在,当我运行它时,会创建多个分支文档,但每个分支文档都会复制第一个现有分支,而不管存在多少分支文档。如何修改var currentBranchId = Branches.findOne({})._id;
以获取此_id
并正确循环设置?
编辑编辑以收集答案
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 "tree-repeat":
return Meteor.call('treeRepeat', currentTreeId, function () {
branches.forEach(function(b) {
var currentBranchId = b._id;
Meteor.call('treeBranchesRepeat', currentBranchId, function (branchId) {
});
});
});
break;
…
}
}
});
Meteor.methods({
treeRepeat: function(currentTreeId) {
check(currentTreeId, String);
var tree = Trees.findOne({_id:currentTreeId}, {fields:{_id:0, treeBranches:0}});
var treeExtended = _.extend(tree, {
treeBranches: [?]//NEED IDS FROM NEW BRANCHES
});
var treeId = Trees.insert(treeExtended);
return {
_id: treeId
};
},
treeBranchesRepeat: function(currentBranchId) {
check(currentBranchId, String);
var branch = Branches.findOne({_id:currentBranchId}, {fields: {_id: 0}});
var branchId = Branches.insert(branch);
return {
_id: branchId
};
}
});
答案 0 :(得分:0)
您可以使用forEach
迭代光标(就像数组一样),例如:
var cursor = Branches.find();
cursor.forEach(function(b){ // b will be a single branch document
console.log(b._id); // you can get its _id directly
console.log(b.branchName); // or any other key
});
对游标执行forEach()
然后在循环中执行findOne
是没有意义的,因为forEach()
将依次将每个对象传递给匿名函数。
从您的问题中不清楚您如何确定哪个分支属于哪个树。
如果我想创建原始Trees
集合的非规范化副本,我可能会执行以下操作:
var treeCursor = Trees.find();
treeCursor.forEach(function(tree){
DenormalizedTrees.insert({_id: tree._id}); // reuse the same _id
tree.treeBranches.forEach(function(id){ // now iterate over the array of branch ids
var branch = Branches.findOne(id);
DenormalizedTrees.update(tree._id,{ $push: { treeBranches: branch }});
});
});