Deleting data that all users use but only for one user in Cloud Firestore - firebase

I am trying to structure my data such that when someone adds a new product to the database, all users receive the new product in their list and therefore the new product appears on their screen.
But if a user decides to delete that product, they can delete it but only for themselves. Is there a Cloud Firestore sorting/ordering/filtering that I should be using to accomplish this?
I thought I could use something like the following:
final theProduct = Provider.of<Products>(context);
products = await firestore.collection('products').getDocuments()
for (product in products.documents) {
await firestore.collection('products').add({
'nameOfProduct': theProduct.nameOfProduct
});
}
But I get a document property error.
Maybe I need to go in one more collection and then try something? But I also need to be able to retrieve the data back using the userID of the signed in user..
Any hints/helpful links would be greatly appreciated.
So I think what I want to do is iterate through all documents within a collection and then document().collection('').add() something to each of their collection. Hopefully that sheds some more light on my problem.

Thanks to those who commented. I found a way to implement this was to use the unique value that each product contains and add it to a list on a per user basis in Firestore. Then fetch that list from Firestore and filter out the corresponding products. No deleting necessary.

Question : a user decides to delete that product, they can delete it but only for themselves
Answer: U can create list in user profile section where u can have all the product document ids & u can use that document id to fetch particular product details & when user click on delete button u can remove that particular document id from there collection
Im not sure what r u doing with sample code over there.
If u want to add data to database then use :
await Firestore().collection('Products').add({
'nameOfProduct': theProduct.nameOfProduct,
});
this will generate document random id for your product.
To get data from particular id use :
DocumentSnapshot documentSnapshot = await Firestore().collection('Products').document('document').get();
then u can use that document snapshot to get data for particular key e.g.
documentSnapshot.data['Product Name']

Related

Choosing the correct Data Structure in Firebase Firestore for my Flutter Todo App

I am currently developing a ToDo app with Flutter and Firebase. The initial situation is as follows:
1. the user has to log in when he wants to create ToDos, i.e. the ToDos would have to be saved best under the UID, right?
2. a user can create multiple lists/categories, for this I also thought about the structure and came up with 2 ideas.
First idea:
I have 2 collections, one with the UserID and all todos and one with the UserID and all categories.
todo ->
title,
createdAt,
done,
category, (link to the second collection with the categories)
...
category ->
name,
icon,
...
Second idea:
I create a single collection per user, the first field is then an array with the name of the category, and in this array are all ToDos.
Unfortunately, I am a complete beginner in Firestore and therefore I am not sure if any of my suggestions would make sense. I hope that the initial situation is well described, otherwise you can still ask questions.
Thank you!
Edit: I just saw a video and I had another idea to create a collection with the UID. This contains all categories as documents and the categories have a subcollection with all Todos.

editing document and field in firebase

im working on firebase and im trying to update the document name and its field name together like shown in the image. i want them to be updated together.
i used this code
EditCourse(String cName, String newName) async {
var collection = FirebaseFirestore.instance.collection("Courses")
..where("Course name", isEqualTo: cName);
collection.doc(cName).update({'Course name': newName});
}
Answer:
As of Now Firebase not allows to update documents ids)
Suggestion:
You should use relational ids or random ids
(relational ids means suppose you have seller favorite collection you can give documents ids to movie/food ids)
There is no way to update the document ID of an existing document. If changing course names is a use-case you need to support, consider using Firestore's built-in ID generation when adding your documents (so add documents using the add() method).
If you stick to your current model, you'll have to:
Read the existing document.
Write the date under the new ID.
Delete the original document.
Given the type of operation, you'll probably want to use a transaction for that.

How to get data from firestore and show in data table? [Flutter]

Situation: In submission page, user have to select society name (dropdown menu), enter title, attach file, and submit it. After user submit the file, the file will be stored in firebase storage, and firestore will save the details under collection("Society Name") > document("date").
Details: File Title, Submission Date, User Id, Url ...
Expectation: I expecting user can check the details of document submitted, the page will show society they belongs to, and a data table showing details (column: File Title, Submission Date).
Currently, I can display the current user's society, using future builder, document snapshot from user details. But I have no idea how to get the document id (except "information") from collection("Society Name"), because the document id I stored in date time format, assume there will be more than 1 document id, storing details about file submitted.
Problem: How can I get the all document id (except "information") and show the details in data table? List view also acceptable.
Really appreciate if anyone can help me or provide me some direction. Thanks.
From what I understand, you want to get all the documents ids in a collection. To achieve this, you would need a query to get all documents in a collection.
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('Society Name').get();
List docs = snapshot.docs;
After you get all the documents, you can now loop the list to get id from the DocumentSnapshot.
docs.forEach((doc){
print(doc.id);
});
For your reference from the official docs:
id → String
This document's given ID for this snapshot.
https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot-class.html
To render as a list widgets you can use ListView.builder together with FutureBuilder

How to filter out matching usernames form firestore database in flutter social media application

So I am creating a Social media appliation with the help of flutter. And in search user page I had created a page where user can search their friends with their Profile names. And in this I used:-
Future allUsersProfile = FirebaseFirestore.instance.collection("users").where("profileName", isGreaterThanOrEqualTo: str).get();
By this I get all the matching profile names.
But when I enter their last name their is no result.
Also I want to convert profile names to lower case and then match.
Also I want that if the search name is in between the saved profile name(for example :- I want to search "arsh" form "Harsh", I can't find the result.
) then also it should give this particular result,
So I want idea that how big social media companies search users.
Can anyone can help me.
Thanks in advance
Assuming you are storing profileName in the same field(including first and last names). i.e, in your Firebase user document, profileName combines both first and last names. You need to do the following:
1- In your Firebase users collection, store a new field for every document called something like 'searchName'.
2- When you store your user info, use this code to to convert profileName into searchName:
String profileName = 'Huthaifa Muayyad`;
String searchName = profileName.toLowerCase().replaceAll(' ', '');
//The .toLowerCase method converts it all to lower case
//The replaceAll, removes the whitespaces.
//Notice the difference between (' ', '').
//This will result in Huthaifa Muayyad => huthaifamuayyad
3- Save both fields in firebase along with all the other info when you create the user.
4- Assuming that str is the input you are getting from the search field, modify your Firebase query to look like this:
Future allUsersProfile = FirebaseFirestore.instance.collection("users").where("searchName", isGreaterThanOrEqualTo: str.toLowerCase().replaceAll(' ', '')).get();
This should solve your problem.

How to update avatar/photoUrl on multiple locations in the Firestore?

In Firestore I am trying to update avatar (photoUrl) on multiple locations when the user changes the avatar.
Data structure: https://i.imgur.com/yOAgXwV.png
Cloud function:
exports.updateAvatars = functions.firestore.document('users/{userID}').onUpdate((change, context) => {
const userID = context.params.userID;
const imageURL = change.after.data().avatar;
console.log(userID);
console.log(imageURL);
});
With this cloud function, I am watching on user update changes. When the user changes avatar I got userID and a photo URL. Now I want to update all "todos" where participant UID is equal to userID.
You could use the array_contains operator for your query. This allows you to search for array values inside your documents.
https://firebase.google.com/docs/firestore/query-data/queries#array_membership
If you found your documents you have to update the URL on all documents and write the updated documents back to the database.
But this causes a lot of unnecessary writes especially if your todos collection gets bigger and you want to archive the todos data.
Simpler solution:
I suspect a to do list does not have more then 10 users if so this is a lot of trouble to save some document reads.
I would recommend you to just load all user documents you need to show the avatar on the to do list.

Resources