Firebase Cloud Function : Cloud Firestore query invalid eventhough data is in Cloud Firestore

Viewed 50

I have a cloud function that has the following code. And I call for query from my iOS app. Even though the data is in the Cloud Firestore collection, the function still go to the else statement meaning console print "NOT IN COLLECTION". can someone help?

cloud function code:

const functions = require("firebase-functions");

const admin = require("firebase-admin");
admin.initializeApp();

const db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;

exports.validateShop = functions.https.onCall((data, context) => {
  const uid = context.auth.uid;
  console.log("Function called by UID: " + uid);
  const email = context.auth.token.email;
  console.log("Email: " + email);

  const shop = data.shop;
  console.log("Recieved: "+ data);

  const docRef = db.collection("Users").where("shopName", "==", shop);
  docRef.get().then(function(doc) {
    if (doc.exists) {
      const docDelete = db.collection("shops").doc(uid);
      const updateDoc = docDelete.doc(uid).update({
        "shopName": FieldValue.delete(),
      });
      console.log(shop + ": EXISTS. DOCUMENT UPDATED ");
      return {success: true};
    } else {
      console.log(shop + ": NOT IN COLLECTION ");
      return {success: false};
    }
  }).catch((error) => {
    return {"shop": "Error getting document"};
  });

  return {
    message: shop,
  };
});

And this is how I call it from my iOS app:

func validateTurn(){
    let data = ["shop": "ThaiSook"]
    
    functions.httpsCallable("validateShop").call(data) { (result, error) in
        print("Function returned")
        if let err = error {print(err)}
        if let res = result {print(res)}
        
    }       
}
1 Answers

If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

Aside of double checking the existence of the document you are trying to get, I recommend you to read the example of getting a document from Firestore with Node.js [1].

You may solve your issue by using in your code the keyword await [2].

[1] https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document

[2] https://javascript.info/async-await

Related