Query firestore database for document id

后端 未结 6 649
梦毁少年i
梦毁少年i 2020-12-01 03:09

I want to query a firestore database for document id. Currently I have the following code:

db.collection(\'books\').where(\'id\', \'==\', \'fK3ddutEpD2qQqRMX         


        
相关标签:
6条回答
  • 2020-12-01 03:52

    Try this:

    db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()
    

    (The first query is looking for an explicit user-set field called 'id', which probably isn't what you want.)

    0 讨论(0)
  • 2020-12-01 03:55

    You can use the __name__ key word to use your document ID in a query.

    Instead of this db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get() you can write

    db.collection('books').where('__name__', '==' ,'fK3ddutEpD2qQqRMXNW5').get().

    In this case you should get an array of length 1 back.

    The firebase docs mention this feature in the rules documentation. https://firebase.google.com/docs/reference/rules/rules.firestore.Resource

    0 讨论(0)
  • 2020-12-01 04:03

    I am a bit late, but there is actually a way to do this

    db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()
    

    This might be useful when you're dealing with firebase security rules and only want to query for the records you're allowed to access.

    0 讨论(0)
  • 2020-12-01 04:07

    Just to clear confusion here

    Remember, You should use async/await to fetch data whether fetching full collection or a single doc.

    async function someFunction(){
     await db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get();
    }
    
    0 讨论(0)
  • 2020-12-01 04:08

    From Firestore docs for Get a document.

    var docRef = db.collection("cities").doc("SF");
    
    docRef.get().then(function(doc) {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
    
    0 讨论(0)
  • 2020-12-01 04:09

    You can get a document by its id following this pattern:

    firebase
      .firestore()
      .collection("Your collection")
      .doc("documentId")
      .get()
      .then((docRef) => { console.log(docRef.data()) })
      .catch((error) => { })
    
    0 讨论(0)
提交回复
热议问题