【问题标题】:I can get all documents but unable to retrieve single document in Firestore我可以获取所有文档,但无法在 Firestore 中检索单个文档
【发布时间】:2021-01-24 02:13:55
【问题描述】:

编辑:

新手错误,我试图通过 ID 引用文档,但由于人为错误,我使用的输入在末尾有空格。

const id = "kahgsdjhagsd " // should be "kahgsdjhagsd"
const usersRef = fb.db.collection('users').doc(id);

========

我正在尝试检索单个文档,但它表明它不存在,尽管事实上当我运行逻辑以获取响应中的所有文档时

    const users = await db.collection('users').get();
    users.forEach(user => {
        console.log(user.id, user.data()) // <-- Works! displays ID...
        const userRef = db.collection('users').doc(user.id)
        if (userRef.exists) {
            console.log("User exists")
        } else {
            console.log("User does not exist") // <-- Getting this though
        }
    })

这很奇怪,如果我将 ID 硬编码为字符串,则以下内容有效:

async getUser() {
    const id = "some-id-to-a-document"
    const usersRef = fb.db.collection('users').doc(id);
    const doc = await usersRef.get();
    if (!doc.exists) {
        console.log('No such document!'); 
    } else {
        console.log('Document data:', doc.data()); // <-- Getting this...
    }
}

但如果我尝试通过函数输入 ID...

async getUser(id) {
    console.log(id) // <-- shows the ID!
    const usersRef = fb.db.collection('users').doc(id);
    const doc = await usersRef.get();
    if (!doc.exists) {
        console.log('No such document!'); // <-- Getting this...
    } else {
        console.log('Document data:', doc.data());
    }
}

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    const userRef = fb.usersCollection.doc(user.id)

    在上述行中,您必须先使用get() 获取DocumentSnapshot,然后才能检查文档是否存在。

    const userSnap = await fb.usersCollection.doc(user.id).get();
    if (userSnap.exists) {
        console.log("User exists")
    } else {
        console.log("User does not exist")
    }
    

    另一个重要的注意事项是,在forEach 中使用 async / await 并不可取,因为它不会总是给出预期的结果。传统的for..loop 可以很好地完成工作。

    【讨论】:

    • 我在这里关注文档:firebase.google.com/docs/firestore/query-data/get-data,这不起作用。唯一可行的方法是硬编码文档 ID。即使我在拨打电话之前确认 ID 存在,它仍然找不到文档。就像它希望它是一个实际的字符串?
    • 是的,这是一个很好的参考。在您的 sn-p 中,当您传递从 firestore 检索到的 id 时,它应该可以工作;我希望fb.usersCollection 有给定ID 的文档
    • 只是想知道db.collection('users')fb.usersCollection 之间的区别。两者都指同一个数据库中的同一个集合?基本上为什么这里有两个firestore 参考?
    • 酷;你试过 - const usersRef = fb.db.collection('users').doc(`${id}`); 吗?
    • 哈哈;很高兴你终于得到它!
    猜你喜欢
    • 2020-10-19
    • 2018-04-21
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 2018-05-13
    • 2019-06-07
    • 2021-05-24
    相关资源
    最近更新 更多