How to add Collection To Document Firestore - firebase

I have a User collection in my Firstore database, and I want to imbed a Workout collection in each document of my User collection. I can do this on the Cloud Firestore Dashboard, but how can I do this when I create a new User document in my Flutter code?
My normal code for adding a user looks like this:
Firestore.instance.runTransaction((transaction) async {
await transaction
.set(Firestore.instance.collection('users').document(uuid_), {
'grade': _grade,
'name': _name,
});
});
but I want to somehow add a Workout subcollection to my newly created User document. Thanks for any help

There is no public API to create a new subcollection. Instead a collection is created automatically when you add the first document to it.
So something like:
transaction.set(
Firestore.instance.
collection('users').document(uuid_).
collection("workouts").document("workoutid"), {
'grade': _grade,
'name': _name,
});

Related

Firebase Document reference where value may change

I have a situation where I have a collection which contains information that displays a user profile picture, this user picture is taken from another collection's (users) document. My problem is that I add a link to the picture when I create the new document, this means that if in future the user changes the profile picture the other collection would not have that new information. Is there a way I can solve this with firebase?
I want to get the data from the other collection whenever the information in users collection is updated.
document value in the collection that needs live data
{profile-picture:"image-from-users-collection goes here"}
document value in /users collection
{user-picture:"my-pic.png"}
I want to get the data from the other collection whenever the
information in users collection is updated.
A mentioned by Mises, one standard approach is to use a Firestore Cloud Function which is triggered when the user document changes.
The following code will do the trick. I make the assumption that the document of the other collection uses the same ID than the user document.
exports.updateUserImage = functions
.firestore
.document('users/{userId}')
.onUpdate(async (change, context) => {
try {
const newValue = change.after.data();
const previousValue = change.before.data();
if (newValue['user-picture'] !== previousValue['user-picture']) {
await admin.firestore().collection('otherCollection').doc(context.params.userId).update({'profile-picture':newValue['user-picture']});
}
return null;
} catch (error) {
console.log(error);
return null;
}
});

How to retrieve all data from a subcollection of all document

I am using Flutter for my app. I want to retrieve all document (not only for one user) of a subcollection and display in the app. Each user has a subcollection of Baggage and a subcollection of Car.
This is how I store in Firebase:
String createAt = DateTime.now().millisecondsSinceEpoch.toString();
var ref = FirebaseFirestore.instance.collection('Trips').doc('userId').collection('Baggage').doc(createAt);
FirebaseFirestore.instance.runTransaction((transaction) async {transaction.set(ref, {
'departure': city1.text,
'destination': city2.text,
'weight': _weightcontroller.text,
'id': userId,
'departureDate': date.text,
'username': firstname,
"timestamp": createAt,
});
});
var ref1 = FirebaseFirestore.instance
.collection('Trips')
.doc('userId')
.collection('Cars')
.doc(createAt);
How to retrieve data from subcollection 'Baggage' for all users. If there is best way so structure these data and retrieve easily, please let me know.
Firestore has something called collectionGroup query where you can get all subcollections if they have same collection name. Which can be done as
FirebaseFirestore.instance.collectionGroup('Baggage').get();
This will give you all the documents across all rooms. For reference documentation

How to copy all documents from one collection to other in Firestore -Flutter?

I am in a situation where when a users makes a payment, his cart products Stored in Firestore collection (CartProducts) should be moved to new collection Called SuccessFullOrders .
So my Basic Question is how to move all documents from one collection to Firestore other Collection in Flutter
I don't Know how to write code for this in flutter.Thanks for your Answers
Here's my Code
void _onPressed()async {
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.currentUser();
print(user.uid);
firestorInstance.collection("users").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
firestorInstance.collection("users").document(user.uid).collection("CartProducts").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
//what to write here so that new documents would be created in other collection
print(result.data);
});
});
});
});
}
Currently there's no way to copy a collection into another provided by firebase officially. And, for sure, you can iterate over your previous collection & create new documents in the other.
In your case you should be doing something like:
userFirebaseInstance
.collection(NewCollection)
.document()
.setData(YourDataHere)

How to create a custom document in collection - Firestore with Flutter

I sign in my user through google, after successfully login. I wants to create document for each user inside user_details collection and the document name should be google id. But its auto generating document name.
Is there any way to create custom document in Firestore?
Thanks in Advance
// Store data in Firestore
storeData(User user) async {
DocumentReference documentRef =
Firestore.instance.collection("user_details").document(user.id);
Firestore.instance.runTransaction((transaction) async {
await transaction.set(documentRef, user.toJson());
print("instance created");
_login.add(Result(Status.SUCCESS, "Login successful.", user));
});
}
Try this await documentRef.setData(user.toJson());

FLUTTER | How to add data to an existing document in firestore

I'm using firestore to store data of my flutter application, and I made a function that creates a document in firestore automatically after the user login
Now I want the user when he fills this form , the data will be added in the same document where the user's email exists.
RaisedButton(
child: Text("Submit"),
onPressed: () {
final CollectionReference users = Firestore.instance.collection('users');
Firestore.instance
.runTransaction((Transaction transaction) async {
CollectionReference reference =
Firestore.instance.collection('users');
await reference
.add({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text});
nameController.clear();
phoneController.clear();
adressController.clear();
});}
I tried this code but it adds new document.
Specify document name before updating database.
Firestore.instance
.collection('Products')
.document('Apple')
.updateData({
'price': 120,
'quantity': 15
});
Here my price and quantity data are numbers. If yours are Strings put String values there.
Best practice is to use transaction.
Make sure that document reference is a reference to a file that you wish to update.
Firestore.instance.runTransaction((transaction) async {
await transaction.update(
documentReference, data);
};
It will make sure that update happens in order in case there are many clients doing it.
In the case of a concurrent edit, Cloud Firestore runs the entire transaction again. For example, if a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.
More info here
Try .setData({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text}, merge: true).
Update 2021:
You need to update the data to add it to an existing document.
var collection = FirebaseFirestore.instance.collection('users');
collection
.doc('doc_id') // <-- Doc ID where data should be updated.
.update({'age' : 20}) // <-- New data
.then((_) => print('Updated'))
.catchError((error) => print('Update failed: $error'));

Resources