Как добавить элемент в коллекцию документов с помощью хранимой процедуры

1

Я хочу добавить коллекцию элементов в документ базы данных космоса, используя хранимую процедуру. Кажется, что что-то не так с хранимой процедурой, которую я реализовал. Что мне не хватает.

Я получаю сообщение об ошибке "Не удалось десериализовать ответ хранимой процедуры или преобразовать его в тип" System.Int32 ": Ошибка преобразования значения {null} для ввода" System.Int32 ""

Я использую следующую хранимую процедуру, чтобы сделать то же самое. Но тщетно.

function spBulkAddStockCountItems(tenantId, stockCountId, stockCountItems) {

    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    var count = 0;

    // Validate input.
    if (!stockCountItems) throw new Error("The array is undefined or null.");

    var stockCountItemsLength = stockCountItems.length;
    if (stockCountItemsLength === 0) {
        getContext().getResponse().setBody(0);
        return;
    }

    tryAdd(stockCountItems[count], callback);

    function tryAdd(doc, callback) {

        var queryDocument = "select * from c where c.tenantId='" + tenantId + "' and c.id='" + stockCountId + "'";

        var isAccepted = collection.queryDocuments(collection.getSelfLink(), queryDocument, {},
            function (err, documents, responseOptions) {
                if (err) throw new Error("Error" + err.message);

                if (documents.length != 1) throw "Unable to find both names";
                stockCountDocument = documents[0];

                stockCountDocument.items.push(doc);

                console.log('done');
            });

        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    function callback(err, doc, options) {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= stockCountItemsLength) {
            // If we have created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        } else {
            // Create next document.
            tryAdd(stockCountItems[count], callback);
        }
    }
}

Это документ, к которому я хочу добавить элементы.

 {
        "items": [],
        "action": null,
        "status": "InComplete",
        "startTime": "2018-05-03T15:34:57.0237016+05:30",
        "finishTime": "0001-01-01T00:00:00",
        "supervisor": {
            "userName": null,
            "phoneNumber": null,
            "pin": null,
            "roleId": "00000000-0000-0000-0000-000000000000",
            "outlets": null,
            "swipeCardInfo": null,
            "id": "00000000-0000-0000-0000-000000000000",
            "name": "admin "
        },
        "outletId": "1884e251-7332-4ff6-9bc6-9b977521fd56",
        "tenantId": "test@testimport6",
        "type": "TIGER.Domain.Models.Stock.StockCount",
        "auditLogs": null,
        "isDeleted": false,
        "id": "9c46c625-2448-4170-b7a2-23ced726f23f",
        "name": null,
        "_rid": "4FsbAPwjFQKcAgAAAAAAAA==",
        "_self": "dbs/4FsbAA==/colls/4FsbAPwjFQI=/docs/4FsbAPwjFQKcAgAAAAAAAA==/",
        "_etag": "\"0000ac54-0000-0000-0000-5aeaded30000\"",
        "_attachments": "attachments/",
        "_ts": 1525341907
    }
  • 0
    Кажется, что запрос, который я использовал для получения конкретного документа, неверен.
Теги:
azure
azure-cosmosdb

1 ответ

0

Я обновил хранимую процедуру, и она работает.

function spBulkAddStockCountItems(tenantId, stockCountId, stockCountItems) {

    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();
    var response = getContext().getResponse();

    var count = 0;

    var stockCountItemsLength = stockCountItems.length;

    // Validate input.
    if (!stockCountItems) throw new Error("The array is undefined or null.");

    if (stockCountItemsLength === 0) {
        getContext().getResponse().setBody(0);
        return;
    }

    tryAdd(stockCountItems[count], callback);

    function tryAdd(stockCountItem, callback) {

        var queryDocument = "select * from c where c.tenantId='" + tenantId + "' and c.id='" + stockCountId + "'";

        var isAccepted = collection.queryDocuments(collection.getSelfLink(), queryDocument, {},
            function (err, documents, responseOptions) {

                if (err) throw new Error("Error" + err.message);

                documents[0].items.push(stockCountItem);

                var isReplaced = collection.replaceDocument(documents[0]._self, documents[0], callback);

                if (!isReplaced) getContext().getResponse().setBody(count);
            });
        if (!isAccepted) getContext().getResponse().setBody(count);
    } 

    function callback(err, doc, options) {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= stockCountItemsLength) {
            // If we have created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        } else {
            // Create next document.
            tryAdd(stockCountItems[count], callback);
        }
    }

}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню