如何使用Azure云功能从CosmosDB中删除文档?

时间:2018-04-28 20:05:03

标签: azure azure-functions azure-cosmosdb

我想出了如何使用Azure云功能在我的CosmosDB实例中创建,读取和更新文档,但仍然不知道如何实现删除。我用作参考的主要文档是https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-cosmos-db-triggered-function

我尝试使用没有id的输入和输出绑定(从而获取整个集合),然后过滤我想要从inputDocuments中删除的项目并将结果设置为outputDocuments。不幸的是,这似乎并没有从数据库实例中删除该项目。知道我可能会缺少什么吗?这样做的正确方法是什么?

这是我写的代码:

const { id } = req.query;
context.bindings.outputDocuments = context.bindings.inputDocuments;
const index = context.bindings.outputDocuments.findIndex(doc => doc.id === id);
const doc = context.bindings.outputDocuments.splice(index, 1);

我也尝试过一个更简单的版本,但这并没有什么区别:

const { id } = req.query;
context.bindings.outputDocuments = context.bindings.inputDocuments.filter(doc => doc.id !== id);

我使用日志语句验证了我的函数正确地更新了上述两种实现的outputDocuments。

以下是我的绑定:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "delete"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "documentDB",
      "name": "inputDocuments",
      "databaseName": "heroesDatabase",
      "collectionName": "HeroesCollection",
      "connection": "ydogandjiev-documentdb_DOCUMENTDB",
      "direction": "in"
    },
    {
      "type": "documentDB",
      "name": "outputDocuments",
      "databaseName": "heroesDatabase",
      "collectionName": "HeroesCollection",
      "createIfNotExists": false,
      "connection": "ydogandjiev-documentdb_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}

1 个答案:

答案 0 :(得分:6)

您可以使用客户端并拨打 DeleteDocumentAsync ,如下例所示

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string customerid, TraceWriter log, DocumentClient client)
{
    HttpResponseMessage response = new HttpResponseMessage();
    try {
        await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri("BankDatabase","Customers", customerid));
        response.StatusCode = HttpStatusCode.OK;
        log.Info($"Deleted customer with id: {customerid}");
    }
    catch (DocumentClientException exc)
    {
        if (exc.StatusCode == HttpStatusCode.NotFound)
        {
            response = req.CreateResponse(HttpStatusCode.NotFound, "There is no item with given ID in our database!");
        }
        else
        {
            response = req.CreateResponse(HttpStatusCode.InternalServerError, "Internal server error. Contact administrator.");
        }
    }

    return response;
}

请在 Azure CosmosDB with Azure functions

上找到完整的回购