How to post data to firestore avoiding non-existent documents?

24 views Asked by At

I have a data structure similar to this that I want to post to firestore database via REST API:

enter image description here

I manually created the House1 document, then Floor1 and Ground.

enter image description here

Ground contains the data:

enter image description here

REST API in R

Now, I am trying to use the firestore REST API in R to create the same thing.

library(httr)
library(jsonlite)

# POST function
post_data_to_firestore <- function(path, data, auth_token) {
  r <- httr::POST(
    url = sprintf("https://firestore.googleapis.com/v1beta1/%s", path),
    config = httr::add_headers(
      "Content-Type" = "application/json",
      "Authorization" = paste("Bearer", auth_token)
    ),
    body = data
  )
  return(r)
}

PROJECT_NAME <- "firebase-project"
COLLECTION <- "Block"
accessTokenu <- "access-token"

endpoint <- paste0("projects/", PROJECT_NAME, "/databases/(default)/documents/", COLLECTION)

data_list <- toJSON(
    list(
    fields = list(
      Name = list("stringValue" = "Ground")
    )
  ), auto_unbox = TRUE
)

post_data_to_firestore(
  path = paste0(endpoint, "/House2/Floor1", "?documentId=", "Ground"),
  data = data_list,
  auth_token = accessTokenu
)

This creates House2 which is a non-existent document according to firestore. I understand that all I have created here is only Ground that contains Name:

enter image description here

Question

How do I change my POST request to ensure that I properly create documents so that I can query them?

3

There are 3 answers

8
Greg Fenton On BEST ANSWER

When you manually added House1 using the Firebase Console, you would have clicked the "Add Document" button for House1, then you clicked "Start Collection" for Floor1, then you clicked "Add Document" for Ground and again for Top.

So manually (via Firebase Console) you created 3 documents:

  • Block/House1
  • Block/House1/Floor1/Ground
  • Block/House1/Floor1/Top

But your REST API is creating a single document:

  • Block/House2/Floor1/Ground
0
Frank van Puffelen On

You'll need to perform a separate POST call for each document in this nested structure. There is no single API call that creates a deeply nested child and all parent documents.

0
Doug Stevenson On

I don't think you need to change post_data_to_firestore. You just need to call it once for each individual document you want to create. Firestore will not automatically create documents in the middle of a path. It will just create the one document for the one path you provide in the request. It works the same way for the client libraries that wrap the underlying protocol.