0
votes

My firestore structure is like this..

enter image description here

i want to import contacts detail on firestore, but also want to check that number is already stored in the collection or not, if not stored than store that number.

my problem is if collection is not exist than nothing work for import contact.

so how i check the main collection is available or not in firestore with react native.

my code for add contact detail to firebase, in this code i get the value from firebase and compare the contact number if it's not stored then store it on firebase.

    const { fetchedContacts, selectedContact } = this.state;
    const {user_id} = this.props

    firebase.firestore().collection(this.props.user_id).get()
    .then((snap) => {
      snap.forEach(async(doc) => {
          fetchedContacts.map((item) => {
            if(item.isSelected == true) {
              if(doc._data.number[0].number !== item.phoneNumbers[0].number) {
                
              } else {
                item.isSelected = false
              }
            }
          });
      });
      fetchedContacts.map((item) => {
        if(item.isSelected == true) {
              addManualContact( 
                user_id,"", item.givenName, item.middleName, item.familyName, "", "", "",
                "", item.phoneNumbers, "", "", item.emailAddresses, "", item.postalAddresses,
                "", "", "", "", "", "", "", "", "", item.birthday, "", "", item.note, 
                item.company, "", item.jobTitle,""
              )
        }
      })
    });

is there any way to check the main collection is available or not before add sub collection value.

1

1 Answers

0
votes

I'm not sure I understand your requirement correctly but you can use snap.exists which is a boolean to check if a doc exists or snap.empty to check if a query is empty.Check the docs So maybe like this

 firebase.firestore().collection(this.props.user_id).get()
    .then((snap) => {
       if(!snap.empty) {
          // work with documents
       } else {
         // Create some documents
       }
    })

Maybe something like that?