【问题标题】:flutter - add to firestore collection if not exists otherwise update颤振 - 如果不存在则添加到 Firestore 集合,否则更新
【发布时间】:2020-03-12 07:26:37
【问题描述】:

在 Flutter 中,我使用 firestore 来存储登录的用户。

如果用户第一次登录,我希望将他的信息添加到集合中。

如果他注销,然后登录,我想在集合中更新他的文档。

要检查是否有与用户对应的文档,我想通过他的“id”来检查,它是文档中的一个字段,而不是文档标签,因为我从 firebase api 获得了“id”。

这是正常工作的添加

_firestore.collection('profiles').add({
        'firebase_id': profile['user_id'],
        'first_name': profile['first_name'],
        'last_name': profile['last_name'],
        'login_date': profile['login_date']
});

我尝试使用以下命令检查用户是否存在,但它总是返回 false

bool isEmpty = await _firestore
            .collection('profiles')
            .where('firebase_id', isEqualTo: profile['user_id'])
            .snapshots()
            .first
            .isEmpty;

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    这里有一个例子,它将检查用户是否存在,如果存在,它将通过简单地使用合并覆盖以前的数据。

    DocumentReference ref = _db.collection('users').document(user.uid);
    
    return ref.setData({
      'uid': user.uid,
      'email': user.email,
      'photoURL': user.photoUrl,
      'displayName': user.displayName,
      'lastSeen': DateTime.now()
    }, merge: true);
    

    }

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      当您在 firestore 中保存用户时,使 documentID 等于 userID。

      Firestore.instance.collection('profiles').document( profile['user_id']).setData({
              'firebase_id': profile['user_id'],
              'first_name': profile['first_name'],
              'last_name': profile['last_name'],
              'login_date': profile['login_date']
      });
      

      然后检查是否存在。

       bool userExists=(await Firestore.instance.collection('profiles').document('userid').get()).exists;
      

      【讨论】:

        猜你喜欢
        • 2020-06-19
        • 2011-10-16
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多