2017-10-10 42 views
0

如何通過posttrigger(JS)更新documentdb中的子文檔數組列?具體來說,如何增加第二選項votecount如何通過posttrigger更新azure documentdb中的子文檔數組列?

{ 
     "name": "Question 1", 
     "options": [ 
      { 
       "Option": "option 1", 
       "id": "1", 
       "votecount": 0 
      }, 
      { 
       "Option": "option 2", 
       "id": "2", 
       "votecount": 0 
      }, 
      { 
       "Option": "option 3", 
       "id": "3", 
       "votecount": 0 
      } 
     ] 
} 
+0

我知道documentdb不支持部分更新,我只需要在替換整個文檔之前遞增votecount值。 –

回答

0

這是如何嘗試更新文檔之前遞增屬性:

document.options [createdDoc.index] .votecount ++;

0

我試圖找到方法來更新部分文件在天青宇宙數據庫但失敗。

It好像天青宇宙db現在不支持partial updates。您可以更新整個文檔stored procedure

示例代碼如下以供參考:

function updateSproc(id, update) { 
    var collection = getContext().getCollection(); 
    var collectionLink = collection.getSelfLink(); 
    var response = getContext().getResponse(); 

    tryQueryAndUpdate(); 

    function tryQueryAndUpdate(continuation) { 
     var query = {query: "select * from root r where r.id = @id", parameters: [{name: "@id", value: id}]}; 
     var requestOptions = {continuation: continuation}; 

     var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) { 
      if (err) throw err; 

      if (documents.length > 0) { 
       tryUpdate(documents[0]); 
      } else { 
       throw new Error("Document not found."); 
      } 
     }); 
    } 

function tryUpdate(document) { 
    var requestOptions = {etag: document._etag}; 

    var fields, i; 

    fields = Object.keys(update); 
    for (i = 0; i < fields.length; i++) { 
     document[fields[i]] = update[fields[i]]; 
    } 

    var isAccepted = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) { 
     if (err) throw err; 
     response.setBody(updatedDocument); 
    }); 
} 

然而,天青波斯菊DB支持MongoDB protocol。您可以在Azure official page上確認。因此,incremental operations支持。請參閱此link

希望它可以幫助你。任何關注,請隨時讓我知道。

+0

謝謝Jay,我沒有使用mongodb驅動程序,我想要做的就是訪問我設法通過以下操作執行的votecount字段:document.Answers [docToCreate.optionId-1] .votecount ++; (我從一開始就這樣做,但錯誤在其他地方) –

+0

@MohammedHamdan那麼,你遇到了什麼錯誤? –

+0

我指的是請求對象,而我應該使用響應對象,響應對象在後觸發器中可用,而請求對象可用於預觸發器 –

相關問題