简体   繁体   中英

How to get the unique id (key) of a document in Firebase database collection?

I am trying to fetch the documents of a collection in my React-Native app but I dont know how to fetch them by ID (key). PS: I dont have any field called unique id or id inside the document but as I have understood, the unique id is the auto-generated key when I create a document which stands as the name of that document (20 characters id).

This is how I fetch all the fields inside a document:

  var ref = firebase.firestore().collection('discounts')
            .orderBy('rest_id')

EDIT :

getDiscounts = () => {
    try {
        this.setState({
            loading: true
        })

        var ref = firebase.firestore().collection('discounts')
            .orderBy('rest_id')
            .limit(this.state.limit)

        ref.onSnapshot((querySnapshot => {
            var discounts = querySnapshot.docs.map(document => document.data());

            var lastVisibleDiscount = discounts[discounts.length - 1].rest_id;
            this.setState({
                discounts: discounts,
                lastVisibleDiscount: lastVisibleDiscount,
                loading: false,
            });
        }));

    }
    catch (error) {
        console.log(error);
    }
}

To print the keys of the documents in the collection in the order of the value of their rest_id field, you can do something like this:

firebase.firestore().collection("discounts").orderBy('rest_id').get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        console.log(doc.id);
    });
});

This is an almost literal copy of the code in the documentation on getting all documents from a collection , so I recommend spending some time there.

You can use (using await/async)

const ref = await ref.get()

It will have an array called docs that you can map over to get the id and data of the document:

const data = ref.docs.map(doc => {return {id: doc.id, data: doc.data()} })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM