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

xxb16uws  于 2022-12-24  发布在  其他
关注(0)|答案(7)|浏览(118)

给定一个Firestore路径,检查该记录是否存在的最简单和最优雅的方法是什么?或者除了创建一个可观察的文档并订阅它之外,还有什么方法?

vwkv1x7d

vwkv1x7d1#

看一下this question.exists看起来仍然可以像标准Firebase数据库一样使用。此外,您可以在github here上找到更多讨论这个问题的人
文件上说

新示例

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);
});

旧示例

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());
}

注意:如果docRef引用的位置没有单据,则结果单据为空,对其进行调用exists返回false。

旧示例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);
    });
1sbrub3j

1sbrub3j2#

如果模型包含太多的字段,在CollectionReference::get()结果上应用一个字段掩码会是一个更好的主意(让我们保存更多的google云流量计划,\o/),所以选择使用CollectionReference::select() + CollectionReference::where()来只选择我们想从firestore得到的是一个好主意。
假设我们有与firestore cities示例相同的集合模式,但文档中的id字段具有与doc::id相同的值,那么您可以执行以下操作:

var docRef = db.collection("cities").select("id").where("id", "==", "SF");

docRef.get().then(function(doc) {
    if (!doc.empty) {
        console.log("Document data:", doc[0].data());
    } else {
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

现在我们只下载city::id,而不是下载整个文档来检查它是否存在。

wr98u20j

wr98u20j3#

检查此:)

var doc = firestore.collection('some_collection').doc('some_doc');
  doc.get().then((docData) => {
    if (docData.exists) {
      // document exists (online/offline)
    } else {
      // document does not exist (only on online)
    }
  }).catch((fail) => {
    // Either
    // 1. failed to read due to some reason such as permission denied ( online )
    // 2. failed because document does not exists on local storage ( offline )
  });
h5qlskok

h5qlskok4#

2022年答案:现在,您可以使用count() aggregation检查文档是否存在 * 而无需下载 *。下面是一个TypeScript示例:

import { getCountFromServer, query, collection, documentId } from '@firebase/firestore'

const db = // ...

async function userExists(id: string): Promise<boolean> {
  const snap = await getCountFromServer(query(
    collection(db, 'users'), where(documentId(), '==', id)
  ))
  return !!snap.data().count
}
vmdwslir

vmdwslir5#

我最近遇到同样的问题,而使用Firebase Firestore和我使用以下方法来克服它。

mDb.collection("Users").document(mAuth.getUid()).collection("tasks").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                if (task.getResult().isEmpty()){
                    Log.d("Test","Empty Data");
                }else{
                 //Documents Found . add your Business logic here
                }
            }
        }
    });

task.getResult().isEmpty()提供了一个解决方案,即是否找到了针对我们查询的文档

wi3ka0sx

wi3ka0sx6#

根据你使用的库,它可能是一个可观察的而不是一个承诺。只有一个承诺会有'then'语句。你可以使用'doc'方法而不是collection.doc方法,或者toPromise()等。下面是一个doc方法的例子:

let userRef = this.afs.firestore.doc(`users/${uid}`)
.get()
.then((doc) => {
  if (!doc.exists) {

  } else {

  }
});

})

希望这能帮上忙...

9w11ddsr

9w11ddsr7#

如果出于某种原因你想用一个可观察的和rxjs的Angular 来代替一个承诺:

this.afs.doc('cities', "SF")
.valueChanges()
.pipe(
  take(1),
  tap((doc: any) => {
  if (doc) {
    console.log("exists");
    return;
  }
  console.log("nope")
}));

相关问题