Karel Debedts
Karel Debedts

Reputation: 5768

Cloud Functions: check if document exists always return exists

I'm checking if a document exists by using this cloud function (Typescript). The problem: the doc doens't exits and it returns exists....

Thank you very much for the help and effort!

export const repeat2 = functions.https.onCall((data, context) => {

  console.log(data.message);
  console.log(data.count);

  const getDocument = admin.firestore().collection('key').doc(data.message).get();

        if(getDocument != null) {
          console.log('EXISTS');
        }

        else {console.log("doens't exist");}

    return {
        repeat_message: data.message,
    }
  });

Upvotes: 5

Views: 3119

Answers (2)

EzeSali
EzeSali

Reputation: 31

if you want to check if is a column in your document is like this:

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if ('ColumnNAME' in doc.data()) {
        //If exists Do somenthing
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such column in the document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

Upvotes: 3

Aleksi
Aleksi

Reputation: 5026

get() returns a Promise, not the actual document. Also, you need to use .exists on the resolved value; check the docs here:

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

Upvotes: 15

Related Questions