So my comments are getting added to the correct post when the comment is made by the author on their own post, like so
The Firestore code updated test:
Future<String> postComment(String postId, String text, String authorId,
String name, String profilePic) async {
String res = 'Some Error occurred';
try {
if (text.isNotEmpty) {
String commentId = const Uuid().v1();
await FirebaseFirestore.instance
.collection('posts')
.doc(authorId)
.collection('userPosts')
.doc(postId)
.collection('comments')
.doc(commentId)
.set({
'profilePic': profilePic,
'name': name,
'uid': authorId,
'text': text,
'commentId': commentId,
'datePublished': DateTime.now()
});
res = 'success';
}
} catch (e) {
res = e.toString();
}
return res;
}
The desired structure of how the comments should get added: posts>UID(of poster)> userPosts(List of their posts)>postID>append comment to this postId as a subcollection.
Now, when I try to create a comment on a post made by another user, a new collection gets started with the ID of the post as its collection name. The postId it gets is the CORRECT id, however, the actual comment itself doesn't get added to the collection of THAT post. As you can see from the circle in the second image, the IDs match, however, the comment made doesn't go where it's intended, as it does in the first image. Does anyone know how I can fix this?
Image with new code test, new collection gets made with the UID of the person who's post I am commenting on, doesn't get added to the subcollection of the actual postId
When you're using the following reference:
await FirebaseFirestore.instance
.collection('posts')
.doc(uid)
.collection('userPosts')
.doc(postId)
.collection('comments')
.doc(commentId)
You're always trying to add data inside a document that corresponds to the currently authenticated user. That's the reason why when you are using the above code with another user, it writes the data to another location. Which location, the one that corresponds to that user.
If you want to write the data under a particular location, you have to create a reference that points to that particular location. For instance, if you want a user to write some data, in a document that corresponds to another user, you have to create a reference that contains that UID. That can be simply done, by adding the ID of the user who creates the post inside the document. In that way, doesn't matter which user reads the post, when you want to write the data, you can use the ID of the user who created the post, to construct the correct path.
Related
i've added a field called like inside a document and i want to add many userId to the like array
uploading methode
var list=[];
await fearbase.collection("users").doc(widget.user)
.collection("PostData").doc(this.ido)
.set({"PostUrl":downloadUrl,"ownerName":loggedInUser.username,"userId":loggedInUser.uid,"timestemp":postId,"PostId":ido,"like":FieldValue.arrayUnion(list)})
.whenComplete(() => Fluttertoast.showToast(msg: "Image Uploaded successfully .i."));
// .then((DocumentReference ido) => ido.update({"PostId":ido.id}))
}
also in this methode (like) i want to add uid to the like array and also count them
Like methode:
void addLike(bool liked) {
// ##################################################
String ido=FirebaseFirestore.instance.collection("PostData").doc().id;
CollectionReference collectReef=FirebaseFirestore.instance.collection("users")
.doc(user!.uid).collection("PostData");
liked =!liked;
if(liked){
DocumentReference reef=collectReef
.doc();
reef.set({
'UserId':user!.uid,
// 'nameAR':loggedInUser.username,
// 'CreationTime':DateTime.now(),
});
```!
every document has his own id (each Post ) and every have fields one of those fields is like(array)
i want to put liked user (uid) in that specific path
How to add new data to firebase, in the picture on the second column there are users, and on the last one there is my note. This note whas created when user created account, and it whas updated when user logged in, before whas "bad location" etc. My problem is to add new note like this, not update it, kepp it, and at the same time, in the same column have some kind of "new collection" with the same 3 strings, but with different data.
class DataService {
final String uid;
DataService({required this.uid});
final CollectionReference notesCollection =
FirebaseFirestore.instance.collection('Notes');
Future createUserData(String notes, String localisation, String title) async {
return await notesCollection.doc(uid).set({
'notes': notes,
'title': title,
'localisation': localisation,
});
}
Future addData(String notes, String localisation, String title) async {
return await notesCollection.doc(uid).set({
'notes': notes,
'title': title,
'localisation': localisation,
});
}
}
This class shows my createUserData, when my user creates account or loggs in, but how to change "addData" in order to have logic as I described above?
if I understand correctly you want to create a new collection for each documents as history. try this:
notesCollection.doc(uid).collection("historic").add({
'notes': notes,
'title': title,
'localisation': localisation,});
I want to order the documents in Firestore. The default Firestore documents list consist of alphabetic characters which get created automatically. But I don't want that. I just want to see my newly added document added at the top of my documents list. How do I do that in flutter? It would be very helpful if you provide me with a code for that. The code I use to create a collection is:
Future<void> userSetup() async {
String user = FirebaseAuth.instance.currentUser?.displayName as String;
CollectionReference users = FirebaseFirestore.instance.collection(user);
final hours = time?.hour.toString().padLeft(2, '0');
final minutes = time?.minute.toString().padLeft(2, '0');
users.add({
"customerId": FirebaseAuth.instance.currentUser?.uid.toString(),
"customerName": FirebaseAuth.instance.currentUser?.displayName,
"customerEmail": FirebaseAuth.instance.currentUser?.email,
"selectedTime": '${hours}:${minutes}',
"selectedDate": DateFormat('dd/MM/yyyy').format(date!),
});
return;
}
But I am unable to set my own document id. Please help me with the issue. Thanks in Advance
From the Flutterfire documentation, the set() method is the one you should be using to be able to specify your own document IDs instead of add(). Keep in mind that if the document ID you specify already exists in your database, the whole existing document will be replaced. This is a sample usage as found in the documentation:
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> addUser() {
return users
.doc('ABC123')
.set({
'full_name': "Mary Jane",
'age': 18
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
It seems that documents are ordered alphabetically in the Firestore console, so your custom document IDs should follow alphabetical order as you require. Not to be confused with retrieving documents from Firestore in a particular order, which is done with the orderBy() method.
I have Doctor collection when each doctor (represent by his email ) has a collection called patients_waiting.
Now, what I'm trying to do is delete one document from the paitents_waiting collection by field calls patients containing his email.
but I tried many solutions and none of them works for me now.
what I have tried to do :
Firestore.instance
.collection("Doctors")
.document(doctorEmail)
.collection("paitents_waiting")
.document(paitentEmail)
.delete();
now it's not good because the document is saved in uid and not by email but I tried to play with the where function but with no success.
how do I found this document by email and delete him?
I will mention that I'm doing it on flutter, but I think it doesn't matter.
as long as you have the patient's email address you can search with and delete it
Firestore.instance
.collection("Doctors")
. document(doctorEmail)
.collection("paitents_waiting")
.where('patient', isEqualTo:paitentEmail )
.get().then((value) => value.docs.single.reference.delete())
Nb: you are using an old version of firestore
Inside your paitents_waiting collection, the documents are NOT named according to patient email, they are randomly generated Firebase IDs. Take a closer look.
Firestore.instance
.collection("Doctors")
.document(doctorEmail)
.collection("paitents_waiting")
.document(paitentEmail) //this in your Firebase isn't an email, it's "xaErf43Asd..etc"
.delete();
If you want to follow this approach, which should be working otherwise, when you want to create a patient waiting document, use .set instead of .add, and set the document id to your pateint's email, like this:
Firestore.instance
.collection("Doctors")
.document(doctorEmail)
.collection("paitents_waiting")
.document(paitentEmail)
.set({your patient data here});
This should get things working for you.
To delete all patients for a doctor by the email you can use a combination of Firestore query and batch updates. The first one we need to get all patients with the same email and the other to delete them. A function for that would look like this:
Future<void> deletePatiensForDoctor(String docEmail, String patEmail) async {
WriteBatch batch = FirebaseFirestore.instance.batch();
QuerySnapshot querySnapshot = await Firestore.instance
.collection("Doctors")
.document(docEmail)
.collection("paitents_waiting")
.where('email', isEqualTo: patEmail)
.get();
querySnapshot.docs.forEach((doc) {
batch.delete(doc.reference);
});
return batch.commit();
}
Can anyone tell me how to create a field Id that is equal to the Document ID. I have done like below however is very inconsistent sometimes the documentID is equal field ID other times not. I want them to always be the save.
void saveOrders() async {
await _db.collection(_collectionOrders).add(
{
"id": _db.collection(_collectionOrders).document().documentID,
}
).then((value){
});
}
thanks in advance.
You could do this in two steps:
Create your document without the id:
DocumentReference doc = await _db.collection(_collectionOrders).add({'your': 'data'});
Update the newly created document and add the id property:
await doc.update({'id': doc.id});
You can now be sure that you inserted the right documentId.