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
Related
I'm making a product display app.
I'm going to create a "Wish List" widget that brings up the product that the user picked as 'wish item'.
I structured it as shown in picture 1.
And to create a widget,
I get all the documents of the collection('wish') of doc('User A').
And with their String values(product name) of the doc,
Get the product data from the collection ('Product') using Query.
The product collection is shown in the picture below.
Is there a more efficient way?
I thought it might be easier to change the data structure.
However, even if I create a new Collection('Wish'), at the same level as Collection('Product'), and put the product's name and user's e-mail in it,
I need to focus on the 'Product' collection with the 'Product name'.
Because I have to use the price, brand, name of product, in Collection('Product').
Is there any other efficient way I'm missing? Thank you!
Instead of storing the product name in string you can use reference type to store direct reference of the document inside other document.
Example code
DocumentReference ref = db.collection('products').doc('product-document-id');
Map<String,dynamic> data = {
'name' : 'Product A',
'product_ref' : ref, // Product document Reference
};
db.collection("users")
.doc("user-id")
.collection("wish")
.doc("your_product_name")
.set(data);
This will add the wish product with dynamic id.
Now you can directly read the document using the product_ref. You can use something like this
final docRef = db.collection("users")
.doc("user-id")
.collection("wish").doc("your_product_name");
final docSnapshot = await docRef.get();
if (docSnapshot.exists) {
final data = doc.data() as Map<String, dynamic>;
var productRef = data?['product_ref'];
productRef.get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
// you will get your product here
}
});
}
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.
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 am building an Appointment Booking application want to retrieve all my documents from firestore at once on a button click. I used this:
Future<void> userAppointmentHistory() async {
String collectionName =
FirebaseAuth.instance.currentUser?.displayName as String;
String doc_id = "YyWqd9VlB1IdmYoIIFTq";
await FirebaseFirestore.instance
.collection(collectionName)
.doc(doc_id)
.snapshots()
.listen(
(event) {
print(
event.get("selectedDate"),
);
},
);
}
From the above code, I am getting only the specified document id details. So please help me modify the above code so that I get all the document details as I want to display these details on cards as my booked appointment history.
Here you are passing the doc id String doc_id = "YyWqd9VlB1IdmYoIIFTq";
You don't want to pass that if you want the full documents.
just pass the collection reference.
Follow the below code
fetchData() {
CollectionReference collectionReference =
FirebaseFirestore.instance.collection(collectionName);
collectionReference.snapshots().listen((snapshot) {
setState(() {
document = snapshot.docs;
});
print(document.toString);
});
}
Rudransh Singh Mahra,
It's as easy as putting text widget in our application.
Solution
You did it in right way but by mistake you have passed a specific id of documents in doc() as doc('YyWqd9VlB1IdmYoIIFTq'). you just need to remove that id from there and you may get your desired output.
What actually happens :
In your query you pass specific docId. So that it will returns that specified id document from your collection. To get all the documents from that collection you just need to do as follows,
Future<void> userAppointmentHistory() async {
String collectionName =
FirebaseAuth.instance.currentUser?.displayName as String;
// String doc_id = "YyWqd9VlB1IdmYoIIFTq";
await FirebaseFirestore.instance.collection(collectionName).doc().get()
}
And you will get your desired output if collectionName is valid and exist in firestorm database.
In my App a user can have many different gymplans. So I have a collection where every gymplan has his own document. When creating a new plan I want to store the document id inside the document so that I have access to this document with the id.
When creating a new document firestore automatically create a unique id which is fine. But how can I get this id inside my code? So far my code to create a new plan looks like this:
Future createPlan(String planName, List exerciseNames, List rows) async {
return await usersCol.doc(myUser.uid).collection('plans').add({
'planId': /// here i want to save the document id firestore creates
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});
}
You'd have to create the document first. Then use set() instead of add(). So:
final ref = usersCol.doc(myUser.uid).collection('plans').doc();
return await ref.set({
'planId': ref.id,
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});