LoginSignup
32
19

More than 5 years have passed since last update.

Firestoreでドキュメントの作成/編集時刻をサーバ側に任せる方法

Posted at

はじめに

Firebaseの勉強がてらクイズの早押しボタンをVueとFirebaseで作ったんだけれども(クリスマス会のクイズ大会用)、ボタンを押した履歴のタイムスタンプ指定にクライアントの時刻を使いたくないなーと思っていたところ、探してみたらサーバ側に処理を任せる方法があったのでメモ。

serverTimestampを使う

作成日なり更新日なりのフィールドにnew Date()のかわりにfirebase.firestore.FieldValue.serverTimestamp()を使えばOK。それだけ。

サンプル

クライアント側で値設定(よろしくないやつ)

const db = firebase.firestore()
db.settings({
  timestampsInSnapshots: true
})

db.collection('test').add({
  createdAt: new Date()
})

サーバ側で値設定

const db = firebase.firestore()
db.settings({
  timestampsInSnapshots: true
})

db.collection('test').add({
  createdAt: firebase.firestore.FieldValue.serverTimestamp()
})

最初は「Functionsでやらなきゃダメなのかなー」とか思ってたけど楽でよかった。

32
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
19