2017-10-10 79 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

我指的是请求对象,而我应该使用响应对象,响应对象在后触发器中可用,而请求对象可用于预触发器 –

相关问题