Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Firestore document exists and return boolean

I want to make a utility function that returns true or false depending on whether a firestore document in a collection exists.

Below is what I originally wrote, but it returns a promise instead of a boolean.

async function docExists(docName, docId) {
  const docRef = db.collection(docName).doc(docId);

  await docRef.get().then((docSnapshot) => {
    if (docSnapshot.exists) {
      return true
    } else {
      return false
    }
  });
}

Is there a way for it to return a boolean, or is this just the wrong way to approach the problem?

like image 841
jl98 Avatar asked Nov 24 '25 07:11

jl98


1 Answers

There's no need to mix the await and .then syntax like you have in your question. This should be sufficient:

async function docExists(docName, docId) {
  const docRef = db.collection(docName).doc(docId);

  let docSnapshot = await docRef.get();
  
  if (docSnapshot.exists) {
    return true;
  } else {
    return false;
  }
}

Alternatively, through the use of promise chaining, you should be able to simply add the return keyword before the original await docRef.get().then(...) that you have in your question.

like image 74
David Callanan Avatar answered Nov 26 '25 23:11

David Callanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!