Как удалить документ из CosmosDB с помощью облачной функции Azure? - PullRequest
0 голосов
/ 28 апреля 2018

Я понял, как создавать, читать и обновлять документы в моем экземпляре CosmosDB с помощью облачных функций Azure, но все еще не знаю, как реализовать удаление. Основная документация, которую я использовал для справки, была https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-cosmos-db-triggered-function.

Я попытался использовать привязку ввода и вывода без идентификатора (таким образом извлекая всю коллекцию), а затем отфильтровать элемент, который я хочу удалить из 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 голосов
/ 29 апреля 2018

Вы можете использовать клиента и позвонить 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 с функциями Azure

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...