1

I have a collection of settings that I am trying to save for users that login. I'm not finding a built in way to allow me to handle updating timestamps for records that I add.

db = firebase.firestore()
settingsCollection = db.collection('settings')

let userSetting = fb.settingsCollection.doc(this.userId)

//store the settings in firebase
var setWithMerge = userSetting.set({
   createdOn: new Date(),
   updatedOn: new Date(),
   filters: {showTestOrders: show},
   userId: this.userId
 }, {merge: true}).then(ref => {
    //console.log(ref) 
 }).catch(err => {
    console.log(err)
 })

According to docs, the .set() method will create or update records. ( https://firebase.google.com/docs/firestore/manage-data/add-data )

Can someone suggest an efficient way to handle the timestamps? My current approach always updates the createdOn method since records exist. I'd like to NOT update that record if it already exists. I was hoping there is a convenient way to do this.

Thanks!

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
thindery
  • 1,164
  • 4
  • 23
  • 40

2 Answers2

5

Another possibility is to use a set of Cloud Functions for Firebase that are triggered with onCreate() and onUpdate(). In other words the creation and update dates are written in the backend.

See the following answer: How to add timestamp to every collection insert,update in firebase functions for firestore database

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
2

You could perform a transaction on that document, and query and check it in the transaction handler. If the document already exists, you can also see what fields it contains, and only update that document as you see fit from your checks.

But it might be easier if your client code has a sense of when a document is definitely created the first time.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441