Azure功能使用Binder更新DocumentDb文档

Kim*_*men 3 azure azure-functions azure-cosmosdb

之前关于Azure Functions的帖子的后续问题.我需要使用命令式绑定器(Binder)更新DocumentDB中的文档.我真的不明白文档,我找不到任何例子(我或多或少找到一种TextWriter的例子).文档说我可以绑定到"out T",我找不到这个例子.

在运行函数之前说文档看起来像这样:

{
    child: {
        value: 0
    }
}
Run Code Online (Sandbox Code Playgroud)

功能看起来像这样:

var document = await binder.BindAsync<dynamic>(new DocumentDBAttribute("myDB", "myCollection")
{
    ConnectionStringSetting = "my_DOCUMENTDB",
    Id = deviceId
});

log.Info($"C# Event Hub trigger function processed a message: document: { document }");

document.value = 100;
document.child.value = 200;

log.Info($"Updated document: { document }");
Run Code Online (Sandbox Code Playgroud)

根据第二个日志记录行,文档未正确更新.子项未更新(从商店读取时存在)并添加了值.无论哪种方式,都没有任何东西存在.我已经尝试在function.json中添加一个输出,但是编译器抱怨它并且文档声明你不应该有任何输出.

我错过了什么?

bre*_*sam 5

Mathew的样本(使用DocumentClient)有效,但我想澄清你可以使用的另一种方式Binder和输出绑定.

你遇到了两个问题:

  1. Document每次请求子对象时,dynamic 的实现似乎都会返回一个新的对象实例.这与函数无关,但解释了为什么document.child.value = 200不起作用.您正在更新一个实际上未附加到文档的子实例.我将尝试使用DocumentDb人员仔细检查这一点,但这令人困惑.解决这个问题的一种方法是请求a JObject而不是a dynamic.我的代码就是这样做的.

  2. 正如@mathewc指出的那样,Binder不会自动更新文档.我们将在他提交的问题中跟踪这一点.相反,您可以使用输出绑定IAsyncCollector<dynamic>来更新文档.在幕后,我们将调用InsertOrReplaceDocumentAsync,这将更新文档.

这是一个适合我的完整示例:

码:

#r "Microsoft.Azure.WebJobs.Extensions.DocumentDB"
#r "Newtonsoft.Json"

using System;
using Newtonsoft.Json.Linq;

public static async Task Run(string input, Binder binder, IAsyncCollector<dynamic> collector, TraceWriter log)
{        
    string deviceId = "0a3aa1ff-fc76-4bc9-9fe5-32871d5f451b";
    dynamic document = await binder.BindAsync<JObject>(new DocumentDBAttribute("ItemDb", "ItemCollection")
    {
        ConnectionStringSetting = "brettsamfunc_DOCUMENTDB",
        Id = deviceId
    });

    log.Info($"C# Event Hub trigger function processed a message: document: { document }");

    document.value = 100;
    document.child.value = 200;

    await collector.AddAsync(document);
    log.Info($"Updated document: { document }");
}
Run Code Online (Sandbox Code Playgroud)

捆绑:

{
  "type": "documentDB",
  "name": "collector",
  "connection": "brettsamfunc_DOCUMENTDB",
  "direction": "out",
  "databaseName": "ItemDb",
  "collectionName": "ItemCollection",
  "createIfNotExists": false
}
Run Code Online (Sandbox Code Playgroud)