angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

Firestore: How to check if document exists, and create one if it doesn't

Open avilao opened this issue 9 years ago • 35 comments

*AngularFireStore:

Is there a way to check if a document already exists in the database?

Couldn't find an example.

Thank you

avilao avatar Oct 15 '17 18:10 avilao

Don't think you can do it with AFS, and might have to rely on the underlying framework:

this.afs.firestore.doc('/users/asfaf').get()
      .then(docSnapshot => {
        if (docSnapshot.exists) {
          // do something
        }
      });

larssn avatar Oct 16 '17 13:10 larssn

this.afs.doc('/path').take(1).do(d => d.payload.exists())

As of 5.0 rc3 empty sets/docs should be handled correctly.

I am working on an API to make return or create easier.

jamesdaniels avatar Oct 16 '17 19:10 jamesdaniels

@jamesdaniels I import the operator take already but i got error i can't use doc with take operator.

ButhSitha avatar Oct 17 '17 05:10 ButhSitha

I'm doing it manually - hopefully there is a better way?

  this.dataDoc = this.myDataCollectionRef.doc(id); 

  this.data = this.dataDoc.snapshotChanges().map(action => {
        if (action.payload.exists === false) {
            return null;
        } else {
            const data = action.payload.data() as Whatever;
            const id = action.payload.id;
      return { id, ...data };;  
   });

Might be incorrect usage of snapshotChanges(), but its able to determine if something is there. If you wanted to manually create it, I believe you could do that once you've determined it doesn't exist.

dhawken avatar Oct 26 '17 11:10 dhawken

Just popping in to report that neither take() nor do() work (exist) for me on AngularFirestoreDocument

sneurlax avatar Nov 12 '17 18:11 sneurlax

Currently handling this by attempting an update and setting on error as such:

this.afs.doc(`users/${uid}`)
  .update({data})
  .then(() => {
    // update successful (document exists)
  })
  .catch((error) => {
    // console.log('Error updating user', error); // (document does not exists)
    this.afs.doc(`users/${result.uid}`)
      .set({data});
  });

sneurlax avatar Nov 12 '17 19:11 sneurlax

@jamesdaniels example is missing somethings:

  • .snapshotChanges()
  • exists isn't a function, is a property.

So,

this.afs.doc('/path').snapshotChanges().take(1).do(d => d.payload.exists)

vaurelios avatar Dec 15 '17 18:12 vaurelios

i check simply , not sure if that is the right way to do ..

const userRef: AngularFirestoreDocument = this.afs.doc(users/${user.uid}); userRef.valueChanges().subscribe(res=>{ if(res){ // do your perform } } );

Vicky443 avatar Dec 17 '17 08:12 Vicky443

Here's a variation of @sneurlax's example:

//Create an empty document, or do nothing if it exists.
this.afs.doc('users/sam').set({ }, { merge: true });

//Create a document with name property set to 'Sam'.
//If document already exists, it will still set the name property to 'Sam'
this.afs.doc('users/sam').set({ name: 'Sam' }, { merge: true });

buchmiller avatar Feb 04 '18 19:02 buchmiller

@buchmiller But by doing so, it will be a write in the document. A write in the document is more costly in terms of pricing according to firebase pricing. If we can read before we write it will be more cost efficient :)

Zufarsk8 avatar Feb 05 '18 02:02 Zufarsk8

How about searching 2 parameters, like username and email? I am looking for username and email that I type in input.

I think it could be in 2 ways:

  1. Maybe we can do all in one query in where clause using OR statement. I am not sure if firestore support it.

  2. I think we can search the username first. If it return null, we continue search the email. I am looking for this possible way. Any suggestion?

olaini-lature avatar Mar 26 '18 02:03 olaini-lature

FTR: https://angularfirebase.com/lessons/firestore-advanced-usage-angularfire/#4-Upsert-Update-or-Create-Method

// *** Usage
this.db.upsert('notes/xyz', { content: 'hello dude'})
// *** Code
upsert<T>(ref: DocPredicate<T>, data: any) {
  const doc = this.doc(ref).snapshotChanges().take(1).toPromise() 
  return doc.then(snap => {
    return snap.payload.exists ? this.update(ref, data) : this.set(ref, data)  })
}

math-a3k avatar Apr 19 '18 13:04 math-a3k

You can use

db.doc('collectionName/documentId').ref.get().then((documentSnapshot) => {
  console.log(documentSnapshot.exists);
});

jwv avatar May 21 '18 08:05 jwv

Hello,

I am using firestore from firebase(npm) and the property .exists was not available on the querySnapshot:

https://firebase.google.com/docs/firestore/query-data/get-data

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

querySnapshot in that context have a property .empty that I use to know if I get a document or not from the query. Hope this helps too.

miglrodri avatar Aug 31 '18 13:08 miglrodri

@mk4yukkalab do you got workaround to ur concern

And if i need a query like : this.afs.collection('users', ref => ref.where('email', '==', email)) how i can do that?

Vino16491 avatar Aug 31 '18 21:08 Vino16491

And if i need a query like : this.afs.collection('users', ref => ref.where('email', '==', email)) how i can do that?

do you know how do that ??

Hanan0o0 avatar Sep 15 '18 09:09 Hanan0o0

@mk4yukkalab do you got workaround to ur concern

And if i need a query like : this.afs.collection('users', ref => ref.where('email', '==', email)) how i can do that?

do you know how do that ??

Hanan0o0 avatar Sep 15 '18 09:09 Hanan0o0

firestore .collection('YourCollection') .doc('YourDocumentID').set( {a: {b: {c: true}}}, {merge: true} )

This one should work

hafizmowais avatar Nov 12 '18 07:11 hafizmowais

@mk4yukkalab @Hanan0o0 @Vino16491 in angular 6 I manage like that

this.afs.collection('users', (ref) => ref.where('email', '==', email).limit(1)).get().subscribe(users => { if(users.size >= 0) ...do smthg })

JeffGreat avatar Nov 15 '18 22:11 JeffGreat

Currently handling this by attempting an update and setting on error as such:

this.afs.doc(`users/${uid}`)
  .update({data})
  .then(() => {
    // update successful (document exists)
  })
  .catch((error) => {
    // console.log('Error updating user', error); // (document does not exists)
    this.afs.doc(`users/${result.uid}`)
      .set({data});
  });

Trying to do something similar in iOS. I think this should be done in a transaction though because there's plenty of time for data to be written with the ID between the update response and the set. Also, I'm questioning whether this is a good solution since we're using an error in order to proceed.

funct7 avatar Dec 16 '18 20:12 funct7