1

i am trying to develop a service in my angular application that validate if a document already exist in my firestore database. How can i do that?

i have been checking the oficial documentation but i dont find the solution :S

Here is my code.

 user: {
   id: 'user1'
 }

  private usersCollection: AngularFirestoreCollection;

  constructor(private _afs: AngularFirestore) {

    this.usersCollection = _afs.collection('users');

    this.userCollection.doc(user.id).snapshotChanges().subscribe(data => {
      if(data.payload.exist){
         //User exist
      }else{
         //User no exist
      }
    })

when i try this... Always returns false even if the Doc exist...

am i checking correctly if User.id exist as a document in my collection Users?

ScreenShot of my database structure

As you can see in the img, there is a document called User1, why is data.payload.exist false?

Sergio Cano
  • 690
  • 3
  • 13
  • 36
  • 1
    See https://stackoverflow.com/questions/47755588/firebase-cloud-functions-check-db-for-non-existant-data, https://stackoverflow.com/questions/46880323/how-to-check-if-a-cloud-firestore-document-exists-when-using-realtime-updates, https://github.com/angular/angularfire2/issues/1272 – Frank van Puffelen Aug 02 '18 at 04:13
  • thanks for the links that you provided me, but i still with this problem... what is wrong in my code? – Sergio Cano Aug 02 '18 at 05:45
  • Without showing the data that you're trying to read, it's impossible to know if the code is correct. Please edit the question to explain exactly what you're trying to read and why your code should show that a document definitely exists the way you expect. – Doug Stevenson Aug 02 '18 at 05:53
  • @DougStevenson what i want to read is... if there is any document in my /Users' collection called like user.id sorry if i didnt explain it well. english is not my mother language :/ – Sergio Cano Aug 02 '18 at 06:03
  • Right, but you haven't proven to us that the actual document you're looking for in fact does exist. Usually one would provide a screenshot or description of the document that's consistent with the code that's trying to read it. – Doug Stevenson Aug 02 '18 at 06:53
  • @DougStevenson img added , thank you again – Sergio Cano Aug 02 '18 at 09:10

1 Answers1

3

You validate that a document exists by reading it, then checking to see if the result exists. There is no API (on any client platform) that gives a simple boolean result for whether or not a document exists.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441