如何通过REST在Firestore文档上添加/删除数组元素?

问题描述 投票:0回答:1

我想使用数组将来自Arduino的温度读数存储在Firestore数据库中。到目前为止,我(可能很糟糕)的思考方式是阅读文档,在Arduino上执行数组操作,然后将整个数组发送回Firestore。我完全不知道如何通过REST写入Firestore,因此我尚未实现它。这是我的代码:

void writeTemp(String url, int temperature) {
    // writeTemp() appends the given temperature to an array. temperature[0]
    // holds the oldest temperature while temperature[9] holds the first.
    // When a new temperature is put in, the last one is taken out.
    HTTPClient http;

    http.begin(url);
    int httpCode = http.GET();

    // Gets the current temperature array from the provided URL.
    String payload = http.getString();
    Serial.println(httpCode);  // Prints HTTP response code.

    // Calculates the size of the JSON buffer. This is big enough for 11
    // temperature values that are all 3 digits so as long as you're not using
    // this on the Sun you're probably fine.
    const size_t capacity = JSON_ARRAY_SIZE(11) + 14 * JSON_OBJECT_SIZE(1) +
                            JSON_OBJECT_SIZE(4) + 440;

    DynamicJsonDocument doc(capacity);  // Makes the JSON document
    DeserializationError err = deserializeJson(doc, payload);

    // Prints out the deserialization error if an error occurred
    if (err) {
        Serial.print("JSON DESERIALIZE ERROR: ");
        Serial.println(err.c_str());
    }

    // Sets up the array from the JSON
    JsonArray temperatureArray =
        doc["fields"]["Temperature"]["arrayValue"]["values"];

    // Creates a new array object to store the new temperature
    JsonObject newTemp = temperatureArray.createNestedObject();

    // Puts the new temperature in the new array object. For some reason,
    // Firestore stores numbers as strings so the temperature is converted into
    // a string.
    newTemp["integerValue"] = String(temperature);

    // Removes the first (oldest) array object.
    temperatureArray.remove(0);

    // Removes irrelevant data that we got from the Firestore request
    doc.remove("name");
    doc.remove("createTime");
    doc.remove("updateTime");

    String newJson;
    serializeJson(doc, newJson);
    Serial.println(newJson);
}

我将如何将此新的JSON发送回Firestore?我什至这样做对吗?我听说过交易,这听起来像是理论上更好的方式来做我想做的事情,但是我找不到任何指南或可读的文档来了解如何做。我的数据库目前处于测试模式,因此无需担心身份验证。

firestore layout

firebase rest arduino google-cloud-firestore
1个回答
0
投票

Firestore REST API的文档为here

要创建文档,您需要向具有以下格式的URL发出POST请求:

https://firestore.googleapis.com/v1/{parent=projects/*/databases/*/documents/**}/{collectionId}

在请求正文中带有Document的实例。


更具体地说,下面是一个简单的HTML页面中的示例(使用Document库发出HTTP请求)。此代码将在Axios Firestore集合中创建一个新文档。

只需将此文件保存在本地磁盘上,调整collection1的值,然后直接从本地磁盘在浏览器中打开此页面。

<yourprojectID>

为了更新现有文档中的数组,必须将<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <script> var firebaseProjectId = '<yourprojectID>'; var collectionId = 'collection1'; var url = 'https://firestore.googleapis.com/v1/projects/' + firebaseProjectId + '/databases/(default)/documents/' + collectionId; var writeObj = { fields: { name: { stringValue: 'theName' }, initialBudget: { doubleValue: 1200 } } }; axios.post(url, writeObj).catch(function(error) { console.log(error); }); </script> </body> </html> FieldTransform元素一起使用。

此文档的FieldTransform元素摘录:

appendMissingElements:如果当前字段值中尚不存在给定元素,请按顺序追加。如果该字段不是数组,或者该字段尚不存在,则首先将其设置为空数组。

您将在下面找到一个包含appendMissingElements元素的appendMissingElements值的示例。

FieldTransform
© www.soinside.com 2019 - 2024. All rights reserved.