如何获取 Firebase 数据库集合中文档的唯一 id(键)?

4 javascript react-native google-cloud-firestore

我正在尝试在我的 React-Native 应用程序中获取集合的文档,但我不知道如何通过 ID(键)获取它们。PS:我在文档中没有任何称为唯一 id 或 id 的字段,但据我了解,唯一 id 是当我创建文档时自动生成的键,它代表该文档的名称(20 个字符的 id)。

这是我获取文档中所有字段的方法:

  var ref = firebase.firestore().collection('discounts')
            .orderBy('rest_id')
Run Code Online (Sandbox Code Playgroud)

编辑

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 5

要按照字段值的顺序打印集合中文档的键rest_id,您可以执行以下操作:

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

这几乎是文档中有关从集合中获取所有文档的代码的字面副本,因此我建议花一些时间在那里。