javascript - Firebase Firestore : get document ID after adding data offline

标签 javascript firebase google-cloud-firestore offline

我像这样将数据添加到 Firestore:

db
    .collection('foo')
    .add({foo: 'bar'})
    .then(docRef => {
      console.log('Added Foo: ', docRef.id)
      // do some stuff here with the newly created foo and it's id.
    })
    .catch(console.error)

文档创建后,我想使用新文档或特别是它的 ID。文档以有效 ID 存储在本地数据库中。

但是创建文档后如何获取ID?在数据与服务器同步之前, promise 不会被解决。

最佳答案

您甚至可以在本地保存之前获得 Id。你只是用这种方式写数据。

      // Add a new document with a generated id.
     var newCityRef = db.collection("cities").doc();
      var id = newCityRef.key;
      // later...
       newCityRef.set(data);

对于网络,默认情况下禁用离线持久性。要启用持久性,请调用 enablePersistence 方法

firebase.firestore().enablePersistence()
  .then(function() {
      // Initialize Cloud Firestore through firebase
      var db = firebase.firestore();
  })
  .catch(function(err) {
      if (err.code == 'failed-precondition') {
          // Multiple tabs open, persistence can only be enabled
          // in one tab at a a time.
          // ...
      } else if (err.code == 'unimplemented') {
          // The current browser does not support all of the
          // features required to enable persistence
          // ...
      }

要检查您是从服务器还是缓存接收数据,请在快照事件中使用 SnapshotMetadata 的 fromCache 属性。如果 fromCache 为真,则数据来自缓存并且可能陈旧或不完整。如果 fromCache 为 false,则数据是完整的并且与服务器上的最新更新一致。

默认情况下,如果只有 SnapshotMetadata 发生变化,则不会引发任何事件。如果您依赖于 fromCache 值,请在附加监听处理程序时指定 includeMetadataChanges 监听选项。

db.collection("cities").where("state", "==", "CA")
  .onSnapshot({ includeQueryMetadataChanges: true }, function(snapshot) {
      snapshot.docChanges.forEach(function(change) {
          if (change.type === "added") {
              console.log("New city: ", change.doc.data());
          }

          var source = snapshot.metadata.fromCache ? "local cache" : "server";
          console.log("Data came from " + source);
      });
  });

因此,如果您添加新数据并且启用了离线功能,您的数据将被添加到缓存中,并且可以被监听器监听。

});

关于javascript - Firebase Firestore : get document ID after adding data offline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49829714/

相关文章:

list - Flutter未处理的异常: type 'Future<Group>' is not a subtype of type 'Group'

google-cloud-firestore - 是否有响应代码可将 Google Cloud 任务标记为永久失败,以便它不会重试?

javascript - 带有背景png的输入按钮

javascript - 无法读取未定义错误的属性 'filter'

typescript - Cloud Functions Firestore : @types/googlemaps 中的 Firebase-Admin 包 Typescript 错误

reactjs - 取消 useEffect Hook 中的所有异步/等待任务以防止 react 中内存泄漏的正确方法是什么?

javascript - 单击导航链接时如何向下滚动到导航栏

javascript - 在小 div 中加载更多图 block

android - 我现在应该使用什么方法,因为 FirebaseInstanceId.getInstance().getToken() 已被弃用

java - 我可以使用客户端登录中的 Firebase ID token 对使用 Java SDK 的 Java 桌面应用进行身份验证吗?