【发布时间】: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