首页 > 解决方案 > Updating firestore data based on some specific condition in Angular. SnapshotChanges() Issue

问题描述

I have to update the data in realtime with some specific conditions. i.e. in my case, I've to update the databases cloudfirestore based on session id and user ID. Below is the code.

let docIdOfNonExistance = this.firestore.collection(
      'testdb',
      (ref_non_user) =>
        ref_non_user
          .where('userId', '>', result.userId)
          .where('sessionId', '==', result.sessionId)
    );

    docIdOfNonExistance.snapshotChanges().subscribe((ref_non_user: any) => {
      console.log(ref_non_user);
      ref_non_user.forEach((doc_list) => {
        this.firestore
          .collection('testdb')
          .doc(doc_list.payload.doc.id)
          .update({ status: 'pending' });
      });
    });

Everything works perfect, realtime data is correctly updating But the problem is after updating the data it comes to the previous state automatically. and Multiple times update is occurring. I have tried to unsubscribe() method also, but for the second time due to the unsubscribe method, data is not updating real-time.

Also, we can directly update with docId but here I have to update based on sessionId and userId.

Please help me while using in this way how multiple times triggering occurs automatically. I found that this is mostly happening due to snapshotChanges() method.

标签: javascriptangularfirebasegoogle-cloud-firestoreangularfire2

解决方案


最简单的方法可能是将 a 添加take(1)到链中:

docIdOfNonExistance.take(1).snapshotChanges().subscribe((ref_non_user: any) => {
  ...

根据我从文档中可以确定的内容,这也应该有效:

docIdOfNonExistance.get().subscribe((ref_non_user: any) => {
  ...

如果它确实有效,我更喜欢这种语法,因为它更接近底层 JavaScript SDK 的执行方式。


推荐阅读