在 Firestore 中将 forEach 与单个文档查询一起使用?

Utk*_*rsh 1 javascript firebase google-cloud-firestore

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

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

为了从此查询中获取文档,我使用了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));
Run Code Online (Sandbox Code Playgroud)

Utk*_*rsh 8

好的。我想到了。

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