当一些文档(type1)在 CosmosDB 上创建时,我需要使用来自其他文档(type2)的数据更新它们。我决定使用 javascript Azure Functions 和 cosmosDBTrigger、无服务器 Azure 选项。我在绑定(bind)表达式来配置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
}
函数.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 触发器发送文档列表作为负载。由于内容是一个列表,而不是单个对象/文档,因此使用输入绑定(bind)将不起作用(您的 inputDocumentIn
绑定(bind))。
通过检查您的绑定(bind)配置,我注意到的另一件事是,您的输出绑定(bind)正在写入触发器正在监听的同一个容器/帐户,您实际上正在创建一个循环(您编写的文档将再次触发该函数) .
如果您想要触发函数、接收更改(文档
)并生成输出,您通常会循环遍历结果,并将结果输出到不同的容器中。如果您确实需要将输出发送到同一个集合,则需要添加一些逻辑来过滤 documents
列表中的输出。
如果您需要执行查询,则执行可能还需要作为循环的一部分进行,但没有可以帮助您的绑定(bind),您需要有一个 Client并手动执行这些操作。
在输出绑定(bind)中保存文档,我想这也需要在循环中进行(因为您希望每个函数执行保存多个文档)当然可以使用数组:
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;
}
}
关于azure - 如何使用 Azure 函数 Cosmos DB 触发器更新集合中的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328619/