如何使用 Azure 函数 Cosmos DB 触发器更新集合中的文档?

How to update a doc in a collection with Azure function Cosmos DB trigger?

我需要用其他文档 (type2) 在 CosmosDB 上创建时的数据更新一些文档 (type1)。我决定使用 javascript Azure Functions 和 cosmosDBTrigger,无服务器 Azure 选项。我在配置 functions.json 以获取与触发函数的 doc-type2 关联的 doc-type1 的绑定表达式时遇到问题。任何帮助都会很棒。

CosmosDB 文档类型 1:

{
    "type": "type1"
    "id": "123",
    "serial" : "123",
    "lastconf": []
}

CosmosDB 文档类型 2:

{
    "type": "type2"
    "id": "qwe",
    "idtype1" : "123",
    "conf1":1
}

function.json

{
    "bindings": [{
        "name": "documents",
        "type": "cosmosDBTrigger",
        "direction": "in",
        "leaseCollectionName": "leases",
        "connectionStringSetting": "_DOCUMENTDB",
        "databaseName": "db",
        "collectionName": "dbDev",
        "createLeaseCollectionIfNotExists": true
    },
    {
      "name": "inputDocumentIn",
      "type": "cosmosDB",
      "databaseName": "db",
      "collectionName": "dbDev",
      "id": "{idtype1}", // sqlQuery ??
      "connectionStringSetting": "_DOCUMENTDB",
      "direction": "in"
  },
  {
      "name": "inputDocumentOut",
      "type": "cosmosDB",
      "databaseName": "db",
      "collectionName": "dbDev",
      "createIfNotExists": false,
      "connectionStringSetting": "_DOCUMENTDB",
      "direction": "out"
  } ]
}

index.js:

module.exports = async function(context, documents, inputDocumentIn, inputDocumentOut) {
   context.log('JavaScript trigger function processed a request.');

   if (!!documents && documents.length > 0) {

       context.log('Documents: ', documents);

       inputDocumentOut = inputDocumentIn;
       inputDocumentOut.lastconf = documents.conf1; //documents[i].conf1; ??

       context.log('inputDocumentOut: ', inputDocumentOut); 
   }
}

Cosmos DB 触发器发送文档列表作为负载。由于内容是一个列表,而不是单个 object/document,因此使用输入绑定将不起作用(您的 inputDocumentIn 绑定)。

通过检查您的绑定配置我注意到的另一件事是,您的输出绑定正在写入您的触发器正在侦听的相同 Container/Account,您正在有效地创建一个循环(您编写的文档将触发函数)。

在您想要触发函数、接收更改 (documents) 并生成输出的情况下,您通常会遍历结果,并将结果输出到不同的容器中。如果确实需要将输出发送到同一个集合,则需要添加一些逻辑来过滤 documents 列表中的那些。

如果您需要执行查询,执行可能还需要作为循环的一部分发生,但是没有绑定可以帮助您,您需要有一个 Client 并手动执行那些操作。

在输出绑定中保存文档,我想这也需要在循环中发生(因为您希望在每个函数执行时保存多个文档)当然可以使用数组:

module.exports = async function(context, documents, inputDocumentIn, inputDocumentOut) {
   context.log('JavaScript trigger function processed a request.');

   if (!!documents && documents.length > 0) {

       context.log('Documents: ', documents);
       var documentsToSave = [];

       for(var i = 0; i < documents.length; i++)
       {
            var document = documents[i];
            var documentToSave = {};
            // process document, maybe assign property values to documentToSave from document
            documentsToSave.push(documentToSave);
       }

       inputDocumentOut = documentsToSave;
   }
}