[英]I can get all documents but unable to retrieve single document in Firestore
EDIT:编辑:
Rookie error, I was trying to reference a document by ID but the input I was using had space at the end due to human error.新手错误,我试图通过 ID 引用文档,但由于人为错误,我使用的输入最后有空间。
const id = "kahgsdjhagsd " // should be "kahgsdjhagsd"
const usersRef = fb.db.collection('users').doc(id);
======== ========
I am trying to retrieve a single document yet it indicates it does not exist, despite the fact when I run the logic to get ALL documents it is in the response我正在尝试检索单个文档,但它表明它不存在,尽管事实上当我运行逻辑以获取所有文档时它都在响应中
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
}
})
Its very weird, the below works if I hardcode the ID as a string:非常奇怪,如果我将 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...
}
}
But if I try to input an ID via the function...但如果我尝试通过 function 输入 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());
}
}
const userRef = fb.usersCollection.doc(user.id)
常量 userRef = fb.usersCollection.doc(user.id)
In the above line, You have to get the DocumentSnapshot
using get()
before checking the document existence.在上面的行中,您必须在检查文档存在之前使用
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")
}
And another important note, within forEach
using async / await is not preferable as it won't give expected result always.另一个重要的注意事项是,在
forEach
中使用 async / await 是不可取的,因为它不会总是给出预期的结果。 The traditional for..loop
would be good to get the work done.传统的
for..loop
可以很好地完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.