Jan*_*oda 2 javascript node.js firebase google-cloud-firestore
我想要做什么:我想从我在 Firestore 中的集合中获取第一个文档,当涉及到文档中的“描述”时,应该从 ZA 订购。
问题:它告诉我“没有这样的文件!”。虽然它应该输出我 1 个文件。
这是代码:
getPost();
async function getPost() {
const postRef = db.collection('posts');
const doc = await postRef.orderBy('description', 'desc').limit(1).get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
};
Run Code Online (Sandbox Code Playgroud)
您的变量doc
是一个QuerySnapshot对象(不是DocumentSnapshot)。正如您从 API 文档中看到的那样,它没有名为 的属性exists
,因此if (!doc.exists)
始终为 true。
由于 QuerySnapshot 对象总是考虑包含多个文档的可能性(即使您指定了limit(1)
),您仍然必须检查其结果集的大小以了解您获得了多少文档。你可能应该这样做:
const querySnapshot = await postRef.orderBy('description', 'desc').limit(1).get()
if (querySnapshot.docs.length > 0) {
const doc = querySnapshot.docs[0];
console.log('Document data:', doc.data());
}
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您使用 await 从返回的承诺中捕获查询结果,则无需使用 then/catch。
归档时间: |
|
查看次数: |
528 次 |
最近记录: |