如果路径已知,检查 Firestore 记录是否存在的最佳方法是什么? [英] What's the best way to check if a Firestore record exists if its path is known?
问题描述
给定给定的 Firestore 路径,除了创建可观察的文档并订阅它之外,检查该记录是否存在的最简单、最优雅的方法是什么?
查看 这个问题 看起来 .exists
仍然可以像标准 Firebase 数据库一样使用.此外,您可以在 github here
文档 声明
新示例
var docRef = db.collection("cities").doc("SF");docRef.get().then((doc) => {如果(文档存在){console.log("文档数据:", doc.data());} 别的 {//在这种情况下 doc.data() 将是未定义的console.log(没有这样的文件!");}}).catch((错误) => {console.log("获取文档时出错:", error);});
旧例子
const cityRef = db.collection('cities').doc('SF');const doc = 等待 cityRef.get();如果(!doc.exists){console.log('没有这样的文件!');} 别的 {console.log('文档数据:', doc.data());}
<块引用>
注意:如果 docRef 所引用的位置没有文档,则生成的文档将为空,调用exists 将返回false.
旧示例 2
var cityRef = db.collection('cities').doc('SF');var getDoc = cityRef.get().then(doc => {如果(!doc.exists){console.log('没有这样的文件!');} 别的 {console.log('文档数据:', doc.data());}}).catch(错误 => {console.log('获取文档时出错', err);});
Given a given Firestore path what's the easiest and most elegant way to check if that record exists or not short of creating a document observable and subscribing to it?
Taking a look at this question it looks like .exists
can still be used just like with the standard Firebase database. Additionally, you can find some more people talking about this issue on github here
The documentation states
NEW EXAMPLE
var docRef = db.collection("cities").doc("SF");
docRef.get().then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
OLD EXAMPLE
const cityRef = db.collection('cities').doc('SF');
const doc = await cityRef.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.
OLD EXAMPLE 2
var cityRef = db.collection('cities').doc('SF');
var getDoc = cityRef.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);
});
这篇关于如果路径已知,检查 Firestore 记录是否存在的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!