2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

firestoreでユニークな連番を作る

Last updated at Posted at 2020-04-25

諸事情でfirestoreのドキュメントのUID文字列ではなく、
ユニークな数字が必要になったので、がんばる。
RDBのインクリメントID的な存在の何かをfirestoreで。

firebase functions上で作ってるので、クライアントでどうやるかはわかってないです。

async () => {
  const doc = fireStore
    .collection('something_counters')
    .doc('something-groups')
  const uniqueNumber = await fireStore.runTransaction(async (t) => {
    const tDoc = await t.get(doc)
    const newNumber = ((tDoc.data() && tDoc.data().number) || 0) + 1
    await t.set(doc, { number: newNumber }, { merge: true })
    return newNumber
  })
}
  • 適当なcollection ( something_counters ) を用意する
  • documentのIDを適当に指定することで、その単位でユニークな数字を生成できる
  • トランザクションかけながらインクリメントして数字を返す

雑に確認した感じ大丈夫そうだけど、そこまで強い確信もててるわけじゃないので、実は重複しちゃったらごめんさい。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?