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

Dav*_*dad 11 firebase angularfire2 google-cloud-firestore

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

Doe*_*ata 20

看看这个问题看起来.exists仍然可以像标准的Firebase数据库一样使用.此外,你可以找到一些更多的人在github上谈到这个问题在这里

文档的状态

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(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(function(error) {
    console.log("Error getting document:", error);
});
Run Code Online (Sandbox Code Playgroud)

  • 是否不赞成使用get函数? (2认同)
  • 这个答案不再有效。当我使用它时, get 函数返回一个可观察的而不是一个承诺。您需要添加 docRef.ref.get (2认同)

ch4*_*4uw 10

如果模型包含太多字段,最好在结果上应用字段掩码CollectionReference::get()(让我们保存更多谷歌云流量计划,\o/)。因此,选择使用 CollectionReference::select()+CollectionReference::where()来仅选择我们想要从 firestore 获取的内容是一个好主意。

假设我们有与 firestore城市示例相同的集合模式,但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);
});
Run Code Online (Sandbox Code Playgroud)

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

  • 这真的有效吗?我试图在 [Collection Reference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) 下找到 `select()` 方法,但找不到它。 (2认同)
  • @cbdeveloper,[集合参考](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference)继承[Query<T>](https://firebase.google.com/docs/参考/js/firebase.firestore.Query)其中一个具有 ```select()``` 方法。但文档没有显示它:(。您可以在源代码中找到它[reference.ts](https://github.com/googleapis/nodejs-firestore/blob/master/dev/src/reference.ts )。 (2认同)

小智 6

检查一下:)

  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 )
  });
Run Code Online (Sandbox Code Playgroud)