I am trying to create a firebase function HTTP endpoint which will allow the posting of a user ID and return if the user exists in the database or not.
Structure of my database:
User ID = document ID in users collection
What I have tried
I created the following code, which would always return "User does not exist!" even when providing an existing user ID:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.userExists = functions.https.onRequest((request, response) => {
if (request.method !== "POST") {
return response.status(400).send("Please send a POST request");
} else {
const userRef = admin.firestore().collection("users").doc(request.body.userID);
userRef.get().then((doc) => {
functions.logger.info(doc.data());
if (doc.exists) {
response.status(200).send("User Exists!");
} else {
response.status(200).send("User does not exist!");
}
}).catch((err) => {
response.status(500).send(err);
});
}
});
I even tried hardcoding the user ID into the function, with no luck either:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.userExists = functions.https.onRequest((request, response) => {
if (request.method !== "POST") {
return response.status(400).send("Please send a POST request");
} else {
const userRef = admin.firestore().collection("users").doc("DGxyfSrLnzLTp3Adzmm7VL6sOZz2");
userRef.get().then((doc) => {
functions.logger.info(doc.data());
if (doc.exists) {
response.status(200).send("User Exists!");
} else {
response.status(200).send("User does not exist!");
}
}).catch((err) => {
response.status(500).send(err);
});
}
});
Code for calling the function, and output:
import requests
data = { "userID": "DGxyfSrLnzLTp3Adzmm7VL6sOZz2" }
r = requests.post("https://{domain_hidden}.cloudfunctions.net/userExists", data)
print(data["userID"])
print(r.status_code)
print(r.headers)
print(r.text)
I am completely stumped and can only assume now that I am missing something simple, so reaching out here for advice. Thanks.
EDIT -- as requested the code used to create new users
I see now as suggested by @Dharmaraj that the user's IDs are in Italics, meaning they do not actually exist. I actually created the user Docs by creating docs in a user sub collection called plants. The code is as follows:
const plant = await addDoc(collection(firestore, "users", user.uid, "plants"), {
name: plantName
});
Do I need to explicitly create a user document before creating items in subcollections?

