【问题标题】:Using forEach with single document queries in Firestore?在 Firestore 中使用 forEach 和单个文档查询?
【发布时间】:2018-03-15 10:53:01
【问题描述】:

当我知道返回的文档引用数仅为 1 时,我应该如何编写 Firestore 查询?

const query = firebase.firestore().collection('Users').where('mobile', '==', '<some mobile number>').limit(1);

为了从此查询中获取文档,我使用了forEach 循环。有什么方法可以在不使用循环的情况下获取文档及其数据?

let docId;

query.get().then((snapShot) => {
    snapShot.forEach((doc) => {
        docId = doc.id;
    });
    if(docId) {
        // doc exists
        // do something with the data...
    }
}).catch((error) => console.log(error.message));

【问题讨论】:

  • 你不能处理forEach循环中的数据吗? snapShot当时是数组吗?
  • @Icepickle。那是我不确定的。即使我查询的内容是唯一的,我也必须使用我不想用于单个文档引用的 forEach 循环。

标签: javascript firebase google-cloud-firestore


【解决方案1】:

好的。我想到了。

.docs() 方法可用于snapShot 对象,以获取与查询匹配的所有文档引用的数组。

所以,如果我只有一个文档,我可以简单地访问它:

query.get().then((snapShot) => {

    const doc = snapShot.docs[0];

    const docId = doc.id;
    const docData = doc.data();
    // so stuff here...

}).catch((error) => console.log(error.message));

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2020-02-27
    • 2018-12-20
    • 2020-10-11
    • 2019-03-21
    • 2019-04-30
    • 2021-08-02
    相关资源
    最近更新 更多