【问题标题】:Save hierarchical nodes from json file into mongodb using mongoose on a node server使用节点服务器上的 mongoose 将 json 文件中的分层节点保存到 mongodb
【发布时间】:2015-08-11 06:37:37
【问题描述】:

我有一个包含类别列表的 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 在其父节点被存储之前就被存储了。

在这方面我还是个新手,我正在寻找合适的/最佳实践方法来处理对象的异步导入,这些对象依赖于之前创建的对象,就像上面一样。

【问题讨论】:

    标签: javascript json node.js mongodb mongoose


    【解决方案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()
            }
        });
    
    });
    

    【讨论】:

    • 这太棒了!谢谢,我会试一试并标记为已回答!
    • 完美运行!谢谢!
    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 2018-06-15
    • 2021-02-19
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多