2017-06-04 105 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)})