How to change the value of array field in firebase flutter? - firebase

I have an array containing list of image URL in firestore. I want to delete the specific image of certain index when user clicks the delete button. This is how my firebase image array looks like Here's what i've tried
FirebaseFirestore
.instance
.collection(
'adsPost')
.doc(widget.id)
.update({
'${images[_current]}':
''
}).whenComplete(() {
print(
'image removed from firestore');
});

You have two options, to remove it from the list in your app, and then update your firebase document with the new modified listed after the image was deleted.:
.update({"images": images.remove(images[_current])});
Or delete it from Firebase:
.update({"images": FieldValue.arrayRemove([images[_current]])})

Related

Flutter Firestore update document name inside of collection

I am trying to add the ability to update the document name inside of my usernames collection inside my Flutter app. Here is my upload function:
Future<void> updateUsername() {
// Add a new user inside our the Usernames Collection. This is useful to check for username availablilty.
return usernames
.doc(username)
.set({
'uid': uid,
'timeCreated': DateTime.now(),
})
.then((value) => print("Username Added"))
.catchError((error) => print("Failed to add username: $error"));
}
Here is my database setup:
There is no option in firestore to rename a document. The way the most uses is to create a new document with the new name and the data that been in the old document, then delete the old document.
Take a look here: Can I change the name of a document in Firestore?
One more advice, if you're not going to put any data in the usernames documents, then make a document that has the name "usernames" and add them there, that would help to make less reads ... unless you know what you're doing.

Firebase and Kotlin: getting the id of a document issues

I have an interesting issue while playing with Firebase and Kotlin.
val docRef = db.collection("Year")
.document(DB_year.toString())
.collection("Month")
.document((DB_month+1).toString())
.collection("Day")
.document(today)
.collection("write")
.get()
.addOnSuccessListener { result ->
for(document in result) {
println("document_id : " + document.id)
}
}
If you get the document id with this code, you can get it normally.
enter image description here
enter code here
This code cannot get the document id.
val docRef = db.collection("Year")
.document(DB_year.toString())
.collection("Month")
.document((DB_month+1).toString())
.collection("Day")
.get()
Why is it like this?
my firestore collection
enter image description here
enter image description here
As shown in your Firebase console screenshot above, the documents in the Day collection are displayed with an italic font in the Firebase console: This is because these documents are only present (in the console) as "container" of one or more sub-collection but are not genuine documents.
If you create a document directly under the write collection with the full path Year/docYear1/Month/subDocMonth1/Day/subDcoDay1/write/writeDoc, no intermediate documents will be created (i.e. no document in the Month or Day collections).
The Firebase console shows this kind of "container" (or "placeholder") in italic in order to "materialize" the hierarchy and allow you to navigate to the write document but the Day document doesn't exist in the Firestore database. Hence the empty result for your second query
See this answer for more details.
Note that if you want to get the parent ids (docs and collections) for a doc in the write collection, you can use the parent properties of the DocumentReference and CollectionReference.
So you can do something like:
db.collection("Year")
.document(DB_year.toString())
.collection("Month")
.document((DB_month+1).toString())
.collection("Day")
.document(today)
.collection("write")
.get()
.addOnSuccessListener { result ->
for(document in result) {
println("Day_doc_id : " + document.reference.parent.parent?.id)
}
}

How to delete specific document in the collection and with the auto generated id of firebase firestore flutter?

I'm adding a feature in my app i.e. favourite the specific item and save it to firestore. Adding the document is done but when i want to unfavourite the item and delete it from firestore. Than my code will delete all the item in it.So how can I delete specific document.
FirebaseFirestore.instance.collection('user').doc('usr1').collection('favourite').snapshots().forEach((querySnapshot) {
for (QueryDocumentSnapshot docSnapshot in querySnapshot.docs) {
// docSnapshot.id;
print("id of document========${docSnapshot.id}");
var ids = docSnapshot.id;
//deleting the doc with id
db.collection("user").doc("usr1").collection("favourite").doc(ids).delete();
}
});
You should use FieldValue.delete(), like this:
db.collection("user").doc("usr1").collection("favourite").doc(ids).update({'NAMEofYOURfield': FieldValue.delete()});
as mentioned here.

Firestore: cant delete document

this is my function for deleting a document in my "files" collection
Future<void> deleteProgram(String id, String program) async {
try {
print(id + "----" + program);
await firestoreInstance.collection("files").doc(program).delete();
// await firestoreInstance.collection("programs").doc(id).delete();
print("done");
} catch (e) {
print(e);
}
}
program is the id of the document, when i use this nothing gets deleted, even if i hardcode the ID.
this is what my collection looks like:
as you can see, each document in the files collection also has a subcollection called files
what am i doing wrong here?
The only way to delete a collection is to delete each individual document from it. There is no atomic operation to delete a collection.
In your screenshot the opleiding4 is shown in italic, meaning that this document doesn't really exist, and the Firebase console merely shows that name to be able to show its files subcollection.
Once you delete all files from the /files/opeleiding4/files subcollection both that collection and its parent document will disappear from the Firebase console too.
Also see:
Firestore DB - documents shown in italics
How to recursively delete collection in firestore?
How to Delete all documents in collection in Firestore with Flutter

Create documents, sub collections in Firestore via flutter on screen loads

I want to achieve is when flutter screen loads a document should create in firestore in following order.
Document > Sub Collection > Document > Data Fields
I manage to create documents and sub collections in above order, but the first Document appear in italic. That's because the child collection, documents creating before parent document created.
But I couldn't able to fix the issue. I've modified the code now it's not even creating the document. Before this It created in italic mode. Now it's not at all.
Here is the code.
getCurrentUser().then((user) {
DocumentReference todayReference = firestoreInstance.collection('attendance').document(todayDate);
firestoreInstance.collection('profiles').where('user_id', isEqualTo: user).snapshots().listen((onData) {
onData.documents.forEach((f) {
CollectionReference todaySubCollection = todayReference.collection(f.documentID);
DocumentReference attendanceReference = todaySubCollection.document(f["name"].toString().toLowerCase());
Map<String,dynamic> mapData = new Map<String,dynamic>();
mapData['attendance_status'] = true;
mapData['in'] = true;
mapData['out'] = true;
firestoreInstance.runTransaction((transaction) async {
await transaction.set(attendanceReference, mapData);
});
});
});
});
Here getCurrentUser() is returning the logged in user id.
Each profiles assigned to a user.
So, What I'm trying to do is, once user logged in a document should create under attendance collection named today's date.
Then looping through each profiles where user_id is matched with logged in user, the matching results will be store as sub collection under today's date with profiles name field.
Then under the name (document), a transaction needs to run to set details like attendance_status, in & out.
Following images will show how previously documents created.
I need to find a way to create documents, collection without in italic mode. Any help would be appreciated.
"Italicized" documents are virtual/non-existent as mentioned in the docs. If a document only has a sub-collection, it will be a virtual/non-existent document. A workaround for this is by writing fields in the document, like what you've mentioned in the comments.

Resources