16

Hello I'm working on some firebase project and i can save my datas via javascript into firebase database. But i couldn't figure it out to auto increment child value (my child value is duyuru, you can see the details in the below) of my database. I'm sharing my code in below can you give me hints to solve this issue.

  <script>

      // Initialize Firebase
      var config = {
        apiKey: "sample1",
        authDomain: "sample2",
        databaseURL: "sample3",
        storageBucket: "sample4",
      };


      firebase.initializeApp(config);
      var database = firebase.database();

     firebase.initializeApp(config);
  var database = firebase.database();

  function writeUserData(userId, name, email, imageUrl) {
  var kategori1 =  document.getElementById("kategori").value;
  var duyuru1 = document.getElementById("duyuru").value;
  var name1 = document.getElementById("name").value;
  var email1 = document.getElementById("email").value;
  var imageUrl1 = document.getElementById("imageUrl").value;





  firebase.database().ref(kategori1 +"/" + duyuru1).set({
    username: name1,
    email: email1,
    profile_picture : imageUrl1
  });
}

    </script>

and the out is like this

{
    "duyuru1": {
        "email": "kjfdlkl",
        "profile_picture": "dsfsd",
        "username": "meraha"
    }
}

I want to output data like;

{
    "duyuru1": {
        "email": "kjfdlkl",
        "profile_picture": "dsfsd",
        "username": "meraha"
    },

    "duyuru2": {
        "email": "kjfdlkl",
        "profile_picture": "dsfsd",
        "username": "meraha"
    }
}

duyuru (child value) section should be auto increment, That's what i wanted for. Thank you for your answers

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Esat kemal Ekren
  • 516
  • 2
  • 8
  • 28

5 Answers5

31

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.

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for answering my question. But i wanna ask you something when i use that method it created random keys, I just wondering if there is any way to create custom increment with javascript. Like when users add data increased data automatically. For example for the first post duyuru1, second post duyuru2, etc.. – Esat kemal Ekren Aug 21 '16 at 17:25
  • That's number at the end seems like an array index and thus won't scale. The links I provided explain the reasons better than I can do here. If you insist on using custom sequences, you'll have to implement them yourself. Firebase has no built-in support for them. – Frank van Puffelen Aug 21 '16 at 21:31
  • Yes according to link that you gave me its better work with that default property thank you. Your answer give me another look for my app. Have a nice day – Esat kemal Ekren Aug 21 '16 at 21:34
2

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.

Gabriel Garrett
  • 2,087
  • 6
  • 27
  • 45
2

There is no AutoId in firebase but here is a quick way to set as auto id

Forexample ;

1- create yourModel ( which one u gonna send as model to firebase )

2- DatabaseReference firebaseDatabase;

3- firebaseDatabase =FirebaseDatabase.instance.reference();

4- firebaseDatabase.child("table_name").push().set( yourModel.toJson() );

Also for getting data u can write code like that

var result= firebaseDatabase.child("table_name").once().then(
   (DataSnapshot datasnapshot){
     Map<dynamic,dynamic> values= datasnapshot.value;
     values.forEach((key,value){
       print("key:"+key+" value:"+value["name"]);
     });
   }
 );
 print(result);

I tried it and works great

Have a nice day !!!

2

IMHO, I think we should use transaction to save increment_id. Please take a look here: https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

function toggleStar(postRef, uid) {
  postRef.transaction(function(post) {
    if (post) {
      if (post.stars && post.stars[uid]) {
        post.starCount--;
        post.stars[uid] = null;
      } else {
        post.starCount++;
        if (!post.stars) {
          post.stars = {};
        }
        post.stars[uid] = true;
      }
    }
    return post;
  });
}
An Huy
  • 432
  • 3
  • 7
1

You can use for first column key to "USERID + Your_indexNumber(in client var)" etc.

This is very simple method.

Your table must like this:

https://i.stack.imgur.com/k9UI6.png