Auto increment a value in firebase with javascript

[亡魂溺海] 提交于 2019-11-28 01:04:04
Frank van Puffelen

Firebase has no auto-incrementing keys, since those don't work well in massively multi-user systems where clients can be offline for prolonged periods.

Instead, Firebase has its own type of auto-generated keys called push IDs. These push IDs have the same important properties of sequences in many relational databases: they are ordered and sequential. But in addition, they can be calculated client-side, even when the client is not connected to the Firebase servers.

See the Firebase documentation on saving data in lists, this legacy blog post on why arrays don't work well in Firebase and this post on how push ids work.

Firebase recommends using distributed counters: https://firebase.google.com/docs/firestore/solutions/counters

For the document that requires the counter, you'd initialize a subcollection of, say, 10 documents and run transaction increments on a random shard whenever you need a counter incremented.

Then you'd query the collection of shards and sum their counters.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!