如何在 Firebase 中创建自动递增的密钥? [英] How to create auto incremented key in Firebase?

查看:26
本文介绍了如何在 Firebase 中创建自动递增的密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I was wondering if we could create auto increment ID's(Keys) in Firebase like we have in SQL!

I was wanting to create a structure like this

rules:
  Line1:
    1: Smith
    2: Alex
    3: Hello
  Line2:
    1: Brown
    2: Michael

So lets say if I want to add "Erik" to Line 1 it should do it like this

Line1:
    1: Smith
    2: Alex
    3: Hello
    4: Erik

Is it possible have structure like that?

I do know we have

push()

and

childByAutoId()

but this does not fit for my problem. I am working with Swift iOS just.

解决方案

Such sequential keys inherently limit the scalability of a multi-user distributed system that also needs to deal with a lack of connectivity. That's one of the reasons why Firebase doesn't support them.

Instead Firebase has its own key type, called push IDs. Like the sequence you're looking for these are monotonously increasing, and they are also guaranteed to be unique. But the big difference is that push IDs, unlike the sequence numbers of most SQL databases, can be determined client side.

For more information on arrays (which are similar to sequences) in Firebase, see this blog post: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html.

For more information on Firebase's push IDs, see this blog post: https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html

If you still decide that you must use sequential IDs, have a look at Kato's implementation of that here: http://jsfiddle.net/katowulf/5ESSp/. The core of this is keeping a counter property in the database with the current highest sequence number, and then using a transaction to update that.

这篇关于如何在 Firebase 中创建自动递增的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆