Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading