我有一个带有类别列表的JSON文件:
"data": {
"categories": [
{
"id": 1,
"name": "Clothes",
"children": [
"Womens",
"Mens",
"Children",
"Baby",
]
},
{
"id": "13",
"name": "Womens",
"children": [
"Womens Tops",
"Womens Bottoms",
"Womens Accessories",
]
},
{
"id": "33",
"name": "Womens Tops",
"children": []
},
在下面的代码中,我尝试/无法遍历每个节点及其子节点以构建一个path
变量,以便与mongo db中的数据一起存储:
for(var i in obj.data.categories) {
var newCat = {
name: obj.data.categories[i].name,
children: obj.data.categories[i].children
};
//UPDATE OR CREATE
Category.findOneAndUpdate({name:obj.data.categories[i].name},newCat,{upsert: true},
function(err,cat) {
if(err) { return handleError(res, err); }
if(cat.children) {
//BUILD CHILDREN PATHS
for(var j=0;j<cat.children.length;j++) {
var newChildCat = {
name: cat.children[j],
};
newChildCat.path = cat.path ? cat.path+','+cat.name : cat.name;
Category.findOneAndUpdate({ name: newChildCat.name},newChildCat,{upsert: true},
function(childErr, newChildCat) {
if(childErr) { return handleError(res, childErr); }
}
);
}
}
}
);
}
但是,由于javascript以异步方式运行,因此某些节点paths
将在存储其父级之前存储。
我仍然是一个新手,我正在寻找合适的/最佳实践方法来处理依赖于之前创建的对象的异步导入,如上所述。
答案 0 :(得分:1)
使用async模块执行此操作。您需要的功能是async.eachSeries
async.eachSeries(obj.data.categories, function(_cat, cb){
var newCat = {...};
Category.findOneAndUpdate({name:_cat.name},newCat,{upsert: true}, function(err,cat) {
if(cat.children) {
async.eachSeries(cat.children, function(_cat2, cb2){
// the code like above with cb2()
}, cb);
} else {
cb()
}
});
});