问题
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