Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Server Timestamp field to the Object which being added

I have a Challenge object, which has it's own properties and I'm able to add it to the database successfully like this:

DocumentReference challengeRef=usersRef.document(loggedUserEmail).collection("challenges_feed").
                document(callengeID);
challengeRef.set(currentChallenge);

This is how it looks like in the database:

enter image description here

I'd like to make a new field in the database (under this challenge) which called latestUpdateTimetamp. This is how it should look like (I have added it manually):

enter image description here

I have tried to set it in the constructor of the object like this:

private Map<String,String> latestUpdateTimestamp;

public Challenge(String id, String senderName,  String senderEmail) {   
            this.senderName=senderName;
            this.senderEmail = senderEmail;

            this.latestUpdateTimestamp= ServerValue.TIMESTAMP;
        }

But this is what I get in the database:

enter image description here

I'm trying to add the latestUpdateTimestamp to the Challenge and the Challenge object itself to the database at the same call. Is it possible?

Can I somehow add this timestamp as a property to this object before adding it?

I know I'm able to make a new call and add this field, but I'm wondering if it's possible at once.

like image 542
Tal Barda Avatar asked Nov 17 '17 16:11

Tal Barda


People also ask

How do I save a timestamp on firestore?

If you want to use server generated value which would be better so you don't depend on device time, use this: Map<String, dynamic> data = { 'name': userName, 'userUID': userUIDglobal, 'time': FieldValue. serverTimestamp(), }; Firestore.


1 Answers

Yes you can, using a Map. First of all, according to official docs it will be necessary to use an annotation that looks like this:

@ServerTimestamp Date time;

Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.

This is how you can update the latestUpdateTimestamp field with the server timestamp and the challangeId with the desired value at the same time.

DocumentReference senderRef = challengeRef
    .document(loggedUserEmail)
    .collection("challenges_feed")
    .document(callengeID);

Map<String, Object> updates = new HashMap<>();
updates.put("latestUpdateTimestamp", FieldValue.serverTimestamp());
updates.put("challangeId", "newChallangeId");
senderRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}
like image 100
Alex Mamo Avatar answered Sep 30 '22 12:09

Alex Mamo