Firebase - firestore createdAt timestamps - react

后端 未结 1 807
不知归路
不知归路 2021-01-21 04:32

I am trying to figure out how to add timestamps to documents created in my firestore database.

I have read and tried each and every one of the suggestions in this post.<

相关标签:
1条回答
  • 2021-01-21 04:44

    To get the Firestore timestamp, firebase.firestore.FieldValue.serverTimestamp() is the correct call. Here's the catch: this method is only used within a DocumentReference .set() or .update() call (or, I believe, a CollectionReference .add()). For example, when adding a new document to your "contact" collection, you might combine formState with the new property 'createdAt' as you pass it to the .add() method:

    handleFormSubmit(event) {
        // Now, you're getting form state here!
        console.log("SUCCESS!! :-)\n\n", formState);
        fsDB
          .collection("contact")
          .add({
            ...formState,
            createdAt: firebase.firestore.FieldValue.serverTimestamp()
          })
          .then(docRef => {
            console.log("docRef>>>", docRef);
            this.setState({ selectedValue: null });
            resetForm(initialValues);
          })
          .catch(error => {
            console.error("Error adding document: ", error);
          });
    }
    
    0 讨论(0)
提交回复
热议问题