2017-06-04 142 views
0

背景多个文档:更新在一个循环

我用PouchDB(IndexedDB的)用于离线NW.js应用程序,我是新来的没有-SQL。我也使用PouchDB插件Upsert,这个basiclly在后台执行db.get()和db.put()。

问题:
我动态创建ñ文件和其他功能我想在一个循环中UPSERT功能来更新他们,但我必须,我想更新文档。所以循环停止在第一次运行(逻辑上,只是正常的行为)。

有没有办法更新n具有循环中一个函数的文档?

这里是我的代码示例:

var temp = $('#number_discuss_points').val(); 

for (i = 1; i < temp; i++) { 
    var v1= $('#discusspoint_heading' + i).val(); 
    var v2= $('#discusspoint_subheading' + i).val(); 
    var v3= $('#point_number' + i).val(); 
    var v4= $('#dpoint_deadline' + i).val(); 
    var v5= $('#responsible_person' + i).val(); 
    var v6= $('#dp_text' + i).val(); 

    db.upsert(id_body + i, function (sheet) { 
     sheet._id = id_body + i; 
     sheet.discusspoint_heading = v1; 
     sheet.discusspoint_subheading = v2; 
     sheet.point_number = v3; 
     sheet.dpoint_deadline = v4; 
     sheet.responsible_person = v5; 
     sheet.dp_text = v6; 

     return sheet; //Logically, the functions stops here and return everthing with 1 

    }).then(function (result) { 
     console.log(result); 
    }).catch(function (err) { 
     console.log(err); 
    }); 
} 

回答

0

我认为诺兰劳森将沿不久与一个比我更好的答案,但在这里不用反正...在你的循环中,您可以添加每个从数据库返回的承诺.up插入一个数组。在循环后,您可以使用Promise.all处理所有这样的承诺:

var temp = $('#number_discuss_points').val(); 

var promise_list = []; 

for (i = 1; i < temp; i++) { 
    var v1= $('#discusspoint_heading' + i).val(); 
    var v2= $('#discusspoint_subheading' + i).val(); 
    var v3= $('#point_number' + i).val(); 
    var v4= $('#dpoint_deadline' + i).val(); 
    var v5= $('#responsible_person' + i).val(); 
    var v6= $('#dp_text' + i).val(); 

    promise_list.push(db.upsert(id_body + i, function (sheet) { 
     sheet._id = id_body + i; 
     sheet.discusspoint_heading = v1; 
     sheet.discusspoint_subheading = v2; 
     sheet.point_number = v3; 
     sheet.dpoint_deadline = v4; 
     sheet.responsible_person = v5; 
     sheet.dp_text = v6; 

     return sheet; //Logically, the functions stops here and return everthing with 1 
    })); 
} 

Promise.all(promise_list).then(function (result_list) { 
    for(var result in result_list) { 
     console.log(result); 
    } 
    }).catch(function (err) { 
     console.log(err); 
    }); 

诺兰在他的文章“We have a problem with promises”涵盖这很好。

+0

谢谢!我还没有完全做到这一点,但这是朝着正确方向迈出的一步。 –

+0

或者,您可以在'for循环'中生成文档,并使用单个'db.bulkdocs()'操作,这样会更有效。但是,这假定您已经有了现有的文档'_rev'数据来传递或新的文档不存在。但是,上面的'db.upsert()'解决方案更加强大,因为它为我们提供了这一点。 –

+0

这是一个很好的提示。我会稍后再尝试。 –

0

首先创建文档的数组里面一个for循环:

docArray=[] 

for(i=1;i<10;i++){ 
    /* Create doc */ 
    doc={} 
    doc._id=i 
    doc.whatever='The Power of '+ i 
    /* Push doc to array */ 
    docArray.push(doc) 
} 

现在,减少docArray到链式承诺:

docArray.reduce((seq,doc)=>{ 
    return seq.then(()=>{ 
     /*Chain "db.pusert" promise to seq*/ 
     return db.upsert(doc._id,function(docOLD){return doc}) 
    }); 
},Promise.resolve()/* Initial value of seq */) 
.then(res=>{console.log('All "db.upserts" resolved')}) 
.catch(err=>{throw new Error(err)})