How to manage add and update data in Firebase

喜欢而已 提交于 2021-02-11 14:01:29

问题


I'm using Flutter. I would like to add data at first. If email or uid had been registered, I want to update data01/02 or add data01/02.

How can I specify the initial data.

    _firestore.collection('members').add({
    'uid': loginUser.uid,
    'email': loginUser.email,
    'data01': {
        'name': name,
        'img_url': 'https://www.xxx.xxx/xxx.png',
        'data02': {
            'phone': phone,
        }
    }

Please give me advice.


回答1:


Assuming you set your document name to your loginUser.uid you can use:

String rawJson = '{
    "email": loginUser.email,
    "data01": {
        "name": name,
        "img_url": "https://www.xxx.xxx/xxx.png",
        "data02": {
            "phone": phone,
        }
    }';

Map<String, dynamic> updateData = jsonDecode(rawJson); // import 'dart:convert';


final userDocument = await Firestore.instance.document('members/$loginUser.uid');
final userDocumentGet = userDocument.get().then((value) {
      if (value == null || !value.exists) {
      //a document for the member can NOT be found
      Firestore.instance.document('members/$loginUser.uid').setData(updateData);

    } else {
      //a document for the member is found
     Firestore.instance.document('members/$loginUser.uid').updateData(updateData);

    }
});


来源:https://stackoverflow.com/questions/61910157/how-to-manage-add-and-update-data-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!