我正在尝试通过 Arduino 代码的 REST API 调用在 Appwrite 中创建文档。我正在使用函数生成自定义
documentId
,但是当我发送请求时,我从 Appwrite 收到错误响应,指出:
错误:
{"message":"Document with the requested ID already exists. Try again with a different ID or use ID.unique() to generate a unique ID.","code":409,"type":"document_already_exists","version":"1.6.1"}
但是在打印有效负载后,这个
documentId
在我的数据库中不存在。
这是我用来创建文档的代码:
String generateRandomId(int length) {
const char charset[] = "0123456789abcdefghijklmnopqrstuvwxyz"; // Alphanumeric characters for ID
String id = "";
for (int i = 0; i < length; i++) {
int index = random(0, sizeof(charset) - 1); // Ensure the index stays within bounds
id += charset[index]; // Append the character to the ID string
}
return id;
}
void createNotification(String type, String message) {
if (WiFi.status() == WL_CONNECTED) {
if (!userCoop.coopDocId.isEmpty() && !userCoop.medicineModuleDeviceId.isEmpty() && !type.isEmpty() && !message.isEmpty() && !dateTime.isEmpty()) {
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
// Construct the full URL
String url = String(appwriteEndpoint) + "/v1/databases/" + databaseId + "/collections/" + notificationCollectionId + "/documents";
http.begin(client, url); // Specify the destination for the HTTP request
// Set the required headers for the Appwrite request
http.addHeader("Content-Type", "application/json");
http.addHeader("X-Appwrite-Response-Format", "1.6.0");
http.addHeader("X-Appwrite-Project", projectId);
http.addHeader("X-Appwrite-Key", apiKey);
// Create JSON object
StaticJsonDocument<512> doc;
doc["documentId"] = generateRandomId(20);
JsonObject data = doc.createNestedObject("data");
data["deviceId"] = userCoop.medicineModuleDeviceId;
data["coopId"] = userCoop.coopDocId;
data["type"] = type;
data["message"] = message;
data["createdAt"] = dateTime;
data["isRead"] = false;
// Serialize JSON to string
String payload;
serializeJson(doc, payload);
Serial.println("Payload: " + payload); // Debug payload
// Send the POST request
int httpResponseCode = http.POST(payload);
// Check the response code
if (httpResponseCode > 0) {
String response = http.getString(); // Get the response payload
Serial.println("\nCreate Notification Response code: " + String(httpResponseCode));
Serial.println("Create Notification Response: " + response);
} else {
Serial.println("\nError on HTTP Create Notification request");
Serial.println("HTTP Response code: " + String(httpResponseCode));
}
http.end();
} else {
Serial.println("createNotification: Empty variables");
}
} else {
Serial.println("WiFi not connected");
}
}
任何帮助将不胜感激。
我尝试过的:
unique()
传递到 documentId
字段,但这也给了我同样的错误,所以我选择创建自定义文档 ID。documentId
字段,但 Appwrite 向我抛出一个错误,提示“'documentId' 字段是必需的”。我想要什么:
documentId
方法创建具有自定义 unique()
的文档。所以我有两个收藏
coops
和notification
。我上面的代码试图在 notifications
集合中创建一个文档。通知文档需要一个名为 coopId 的属性,该属性将其与 coops
集合中的文档相关联,这也是我收到 “具有所请求 ID 的文档已存在的原因。使用不同的 ID 重试或使用 ID.unique()生成唯一 ID。” 错误是因为 coopId
属性的关系设置为一对一,从而导致了错误。
解决方案是将属性设置为多对一。