I have a field of type array in my firebase database and I want to add to it new values.
What code I want :
Firestore.instance.collection('lists').document(123).setData({
'myList': FieldValue.add(**myValue**);
});
This should work:
Firestore.instance.collection('lists').document(123).updateData({
'myList': FieldValue.arrayUnion(['el1', 'el2'])
});
Related
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());
I am trying to query data from firestore and assign it to a List.
My users collection is as follows
List<String> emailList = ['Select email', 'email1', 'email2'];
I am trying to populate the above emaillist with the emails of persons such that the list is populated by emails of the persons where the groupId is equal to groupId of current user.
I tried querying by Firebase.instance.collection.where but it gets an error saying it cant be assigned to a List.
Any idea on how to do that?
It sounds like the issue is how you are adding to the list. You have to loop through the snapshot query and for each document, add to the list.
Firestore.instance.collection('users').getDocuments().then((snapshot) => {
snapshot.documents.forEach((doc) {
emailList.add(doc.data['email']);
})
});
Hope this helps!
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.
In the firestore collection named 'doctor' there are different fields including the field 'role'. I want to add the doctors into firestore with a role named doctor. How can I do this? Following is the code that successfully adds data into the database. If you can, tell me the way to add data with a specific field name. Thanks in advance.
service.ts
create_Newdoctor(Record){
return this.firestore.collection('doctors').add(Record);
}
component.ts
CreateRecord(docForm: NgForm){
let Record = {};
Record['fullName']=this.fullName;
Record['email']=this.email;
this.DoctorService.create_Newdoctor(Record).then(res=> {
this.fullName="";
this.email="";
console.log(res);
this.message = "Added";
}).catch(error=>{
console.log(error);
});
}
Notice that Record is a javascript object, and how you create a document in Cloud firestore, is by passing an object with all the filled attributes into the add method like what you did in service.ts, and how you pass in an attribute is via Record[ATTRIBUTE_NAME] = ATTRIBUTE_VALUE
Hence I believe what you need to just to add in the line Record[‘role’] = “doctors” into component.ts
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