Search code examples
firebaseionic-framework

firebase - pushing an object to an array angularFire2


I have a db in which I want to store data like this:

Books:
    0:{pushed Object}
    1:{pushed object} ...

As if it is an arrays so I can iterate over it and do the stuff I need to do. The problem is that I am storing data as pic related shows: pic related

It is storing the object with the push_ID firebase assigns to an object but not with the index of an array. This is how I am pushing the object to my database:

let book_data = {
  id: bookId,
  name: bookData.name,
  author: bookData.author,
  genre: bookData.genre,
  publishDate: bookData.publishDate
};
this.fb.list(`my-lists/${bookList.name}/books/`).push(bookData);

What am I doing wrong?

If needed, I'm coding this for an ionic project.


Solution

  • If you use push() method, Firebase assign it a unique ID without you doing anything else. so if you want a custom key that you defined, you can use set() to save data to a specified reference, also it can be replacing any existing data at that path.

    let book_data = {
      id: bookId,
      name: bookData.name,
      author: bookData.author,
      genre: bookData.genre,
      publishDate: bookData.publishDate
    };
    
    let yourkey = 0;
    
    this.fb.list(`my-lists/${bookList.name}/books/${yourkey}`).set(bookData);
    

    When you set new object next time, you have to change the key again and save data