Sergino
Sergino

Reputation: 10838

Add timestamp insteard auto-geenrated key in firebase document

I want to be able to query the latest document from the firebase, and I fount that I have to refer to the timestemp.

However in my database I do have auto-generated id's

enter image description here

I did came across this question How to retrieve the last document in a firebase collection. I would also like to get the document fields value and discovered that you can have time stem instead of the keys.

I adding and updating the data to firebase like that:

 firebase.firestore().collection(collectionName).add({
        data: data,
        updated: getDate()
      });

firebase.firestore().collection(collectionName).doc().update({
        data: data,
        updated: getDate()
      });

So I wonder how would you achieve using the date as a keys
enter image description here

Upvotes: 0

Views: 91

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317798

If you need to a specific string to be the ID of the document, then you can't use add(), and also can't use doc() with no parameters. You will need to build the string yourself, and pass it to doc().

Personally, I don't recommend this. I suggest accepting the random ID, and instead use a server timestamp as a field in the document. You can use that to sort the results of a query, and limit the result set to 1 in order to get the newest document.

Upvotes: 1

Related Questions