且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果路径已知,检查 Firestore 记录是否存在的***方法是什么?

更新时间:2022-10-18 18:32:26

查看 这个问题 看起来 .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);
    });