0

I have a Cloud Firestore collection for user vehicles. Each document is tied to the user's UID from authentication. I have managed to write out a custom Vehicle POJO to the collection, but I can only write one vehicle at a time.

How can I handle so that each time the user adds another vehicle, it adds it to the document as an array? So you'd have vehicle[0], vehicle[1] and so on.

1 Answer 1

0

How can I handle so that each time the user adds another vehicle, it adds it to the document as an array?

You can achieve this by simply calling update() method like in the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference vehicleIdRef = rootRef.collection("vehicles").document("vehicleId");
Vehicle vehicle = new Vehicle("VehicleName");
vehicleIdRef.update("vehicleArray", FieldValue.arrayUnion(vehicle));

Which will atomically add a new "Vehicle" object to the "vehicleArray" array field. More informations here.

Please also note, that this technique will work only if you don't have a Date property in your class, otherwise you'll get an error like this:

Caused by: java.lang.IllegalArgumentException: Invalid data. FieldValue.serverTimestamp() can only be used with set() and update()

Sign up to request clarification or add additional context in comments.

4 Comments

Hey Alex! Sorry, been on a min-vacation from code :) I was able to get that working. Follow up (if you don't mind) - how can I get them back out? I am currently have a vehicle Document that is the user UUID and nested Vehicle objects under them. But when I try to retrieve, I end up getting a blank object. I am also writing out the user's UUID to the Vehicle object so I can query based on fields that contain that UUID.
To provide a little more info, I am able to get the nested values out by converting to a Map and calling getData on the DocumentSnapshot. Then looping over the Map entry set. I have typically used Firestore's methods to convert the result back over to my custom object (e.g. documentSnapshot.toObject(POJO.class), but since I am getting the nested values as a Map, will I need to use something like Jackson or GSON?
Good to hear that it worked :) "how can I get them back out?" I cannot say much without seeing the code. So I recommend you to post another fresh question, so me and other Firebase developers can help you.
Done! Thanks for helping a newbie out :) stackoverflow.com/questions/54545018/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.