EN VI

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

2024-03-16 06:00:08
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.

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
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login