问题
I'm adding a document to a firestore collection (inboxItems) onSubmit of a form.
onCreateInboxItem = event => {
this.props.firebase.inboxItems().add({
name: this.state.newInboxItemName,
created: '', // I need a timestamp field here
})
this.setState({ name: '' });
event.preventDefault();
}
How do I get the created field to be a timestamp field, with current timestamp as a value? It would need to be consistent across users and timezones.
I see firebase.firestore.FieldValue.serverTimestamp() mentioned in the firebase docs, but at this point the field value isn't set yet. I would like to avoid an extra operation to update the field.
回答1:
You can do:
created: new Date(),
or:
created: firebase.firestore.Timestamp.fromDate(new Date()),
Alternatively you could use a cloud function, as described here, though that might be overkill.
回答2:
Since I use firebase authentication, I initialize firebase with the root App component via the context API. I managed to solve it by adding a helper in my Firebase settings file:
class Firebase {
constructor() {
app.initializeApp(config);
/* Helper */
this.fieldValue = app.firestore.FieldValue;
/* Firebase API's */
this.db = app.firestore();
}
}
And then:
this.props.firebase.inboxItems().add({
created: this.props.firebase.fieldValue.serverTimestamp(),
name: this.state.newInboxItemName,
})
来源:https://stackoverflow.com/questions/55753570/setting-a-created-timestamp-in-firestore-with-react