How to update Map Value in Flutter Firebase Firestore - firebase

I have a Map object in my document data. Like Below
I have to add a new user bid to the same map without erasing old data but the code I used was replacing the whole Map with the new value. Any suggestions on how to achieve my goal.
FirebaseFirestore.instance.collection('products')
.doc(widget.product.uid).update({
'bids': {
auth.currentUser?.email:
currentPrice.toString()
}
});

You need to use dot notation to update a nested field:
const userEmail = auth.currentUser?.email;
FirebaseFirestore.instance.collection('products')
.doc(widget.product.uid).update({
'bids.${userEmail}': currentPrice.toString()
});
Dot notation allows you to update a single nested field without overwriting other nested field. If you update a nested field without dot notation, you will overwrite the entire map field
References:
Update fields in nested objects
FlutterFire Documentation
To update fields with . in their keys:
var fPath = FieldPath(["bids", "user.name#domain.tld"]);
FirebaseFirestore.instance.collection('products').doc(widget.product.uid).update(fPath, currentPrice.toString());

Related

Flutter : How to add element to map field inside firebase database?

I'm trying to find a way to add element to map field inside firebase database from my flutter code. The element as well is a map. So it's a nested map.
Future updateImageDate({
String token,
int rating,
int like,
int display_count,
//Map participants,
}) async {
return await pictureCollection.document(token).updateData({
'rating': rating,
'like': like,
'display_count': display_count,
//'participants': participants,
// I want to add only one element to this existing map field in firebase database.
// Although currently it's empty, I want to keep add new element every time I use this method.
// The element as well is a map. So it's a nested map.
});
}
Please help me! I'm looking forward to hearing from you. Thank you in advance. :D
To write to a map, use dot (.) notation. So:
pictureCollection.document(token).updateData({ 'path.to.field': 'new value' });

Firestore adding to map without deleting

Im trying to add to a map field but when i try this line it replaces the current fields under the map. How can I add new elements to a map without replacing the current values?
var document = await db.collection("trips").document(widget.tripInfo.documentID).updateData({
'members': {
name : id,
},
});
If you want to update a nested field, use dot notation:
db.collection("trips").document(widget.tripInfo.documentID)
.updateData({ 'members.name': id })
Also see the Firebase documentation on updating fields on a nested object.

How can I update nested List in Map that's all inserted to a List? Eg. List<Map<String, dynamic>>

I am trying to update or add to the end of the Lists that are in a Map and all inserted into a List that contains those maps. The List name is 'classes', what I have tried doing was using dot notation, so classes.index.example, but that doesn't work. Why...let's say I have two indexes in the list, If I go ahead and update index 0, the 'questions' and 'answers' will get inserted into that correct index, But for some reason, it will delete index 1 and any other that was created. It's as if It's overwriting all the data, but I don't understand why, I am not using 'setData()' Also, if I leave 'title' out, that too will get deleted??
Future updattingUserData(int index, List<dynamic> question, List<dynamic> answer, String title) async {
return await _collref.document(uid).updateData({
"classes.$index.questions": FieldValue.arrayUnion(question),
"classes.$index.answers": FieldValue.arrayUnion(answer),
//"classes.$index.title": title
});
}
Firestore doesn't have the capability of changing an array element knowing only its index within an array field. What you will have to do is read the document, modify the classes array in memory, then update the entire classes array field back to the document.

Flutter: How to remove a specific array data in firebase

I'm having a problem right now in firebase. Where I try to delete/remove a specific array data. What is the best way to do it? Ps. I'm just new in firebase/flutter.
My database structure:
Data that i'm trying to remove in my database structure(Highlighted one):
First create a blank list and add element in the list which you want to remove then Update using below method
Note : For this method you need the documennt id of element you want to delete
var val=[]; //blank list for add elements which you want to delete
val.add('$addDeletedElements');
Firestore.instance.collection("INTERESTED").document('documentID').updateData({
"Interested Request":FieldValue.arrayRemove(val) })
Update:
Much has changed in the API, although the concept is the same.
var collection = FirebaseFirestore.instance.collection('collection');
collection
.doc('document_id')
.update(
{
'your_field': FieldValue.arrayRemove(elementsToDelete),
}
);
Firestore does not provide a direct way to delete an array item by index. What you will have to do in this case is read the document, modify the array in memory in the client, then update the new contents of the field back to the document. You can do this in a transaction if you want to make the update atomic.
This will help you to add and remove specific array data in could_firestore.
getPickUpEquipment(EquipmentEntity equipment) async{
final equipmentCollection = fireStore.collection("equipments").doc(equipment.equipmentId);
final docSnap=await equipmentCollection.get();
List queue=docSnap.get('queue');
if (queue.contains(equipment.uid)==true){
equipmentCollection.update({
"queue":FieldValue.arrayRemove([equipment.uid])
});
}else{
equipmentCollection.update({
"queue":FieldValue.arrayUnion([equipment.uid])
});
}
}
Example

How to get the id/key of added firebase item directly in Ionic 2?

I'm trying to get the id/key of added item after adding processing
for example, this is my add function
add(){
let todayTime = moment().format('YYYY-MM-DD, HH:mm')
this.afd.list('/questions/').push({
uemail: this.userService.email,
title: this.variables.title,
text: this.variables.text,
type: this.variables.type
})
}
So how can I get the id directly (when item added successfully) ?
According to firebase doc
let key = this.afd.list('/questions/').push().key;
You get the key before pushing your data. It is useful when you need simultaneously add data in different locations using .update()

Resources