0

What I want to achieve is to check if a document exist based on a field like liker_id and if it exist then return and if not then create a new document with the liker_id.

I've tried both snapshot.exists and doc.exists but they seem to give weird behaviors where the console.log doesn't get triggered or collection still adds document even though it already exists.

const liker = db
  .collection("post")
  .doc('ubxL0nDCLHgrtEyQ5TEV')
  .collection("votes")
  .where("liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3")
  .get()
  .then(snapshot => {
    snapshot.forEach(doc => {
      if (doc.exists) {
        console.log("exist");
      } else {
        console.log("not exist");
      }
    });
  })
  .catch(error => {
    console.log(error);
  });
rendell
  • 917
  • 2
  • 9
  • 26
  • There is a similar question [here](https://stackoverflow.com/questions/46880323/how-to-check-if-a-cloud-firestore-document-exists-when-using-realtime-updates) – Ricardo Ramirez Feb 24 '20 at 14:48
  • I'm not sure I understand what behavior you are seeing. Are you saying that `not exist` gets printed even when a document with `"liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3"` already exists? All you should need to do is check [`QuerySnapshot.empty`](https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot#empty), without the need for a loop. – Frank van Puffelen Feb 24 '20 at 15:26
  • I tried "snapshot.empty" but it just returns "true" whether the collection is empty or not. – rendell Feb 24 '20 at 15:48

1 Answers1

0

Would you try the code like this?

const liker = db
  .collection("post")
  .doc('ubxL0nDCLHgrtEyQ5TEV')
  .collection("votes")
  .where("liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3")
  .get()
  .then(snapshot => {
    const data = snapshot.val();
    data.forEach(doc => {
      if (doc.exists) {
        console.log("exist");
      } else {
        console.log("not exist");
      }
    });
  })
  .catch(error => {
    console.log(error);
  });
Osman Safak
  • 255
  • 1
  • 5
  • `const data = snapshot.val();` is code for the Realtime Database, while OP is using Cloud Firestore. While both databases are part of Firebase, they have different APIs. – Frank van Puffelen Feb 24 '20 at 15:25