How to check if a cloud firestore document exists when using realtime updates

前端 未结 1 1894
野性不改
野性不改 2020-12-06 08:43

This works:

db.collection(\'users\').doc(\'id\').get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      db.collection(\'users\').doc(\'id\')         


        
相关标签:
1条回答
  • 2020-12-06 09:19

    Your initial approach is right, but it may be less verbose to assign the document reference to a variable like so:

    const usersRef = db.collection('users').doc('id')
    
    usersRef.get()
      .then((docSnapshot) => {
        if (docSnapshot.exists) {
          usersRef.onSnapshot((doc) => {
            // do stuff with the data
          });
        } else {
          usersRef.set({...}) // create the document
        }
    });
    

    Reference: Get a document

    0 讨论(0)
提交回复
热议问题