Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert new child data in Firebase web app?

I am building a simple car database app. When a user adds a new car it creates the below JSON data with blank fields for the gallery:

{
    "name": "Cars",
    "gallery": [{
        "img": "http://",
        "title": "BMW"
    }, {
        "img": "http://",
        "title": "Lexus"
    }, {
        "img": "http://",
        "title": "Ferrari"
    }],
    "pageId": "23",
    "storeURL": "/app/cars/gallery"
}

Now what I want to do in the app is if a user adds a new gallery image it should add new child after the last gallery picture. So after Ferrari it should insert a new object. I cannot seem to do this as every tutorial leads to a dead end and also the official Google docs specify that set() will replace all data so if you use update() it will add and in this case it does not add.

This code deletes all data:

function add(){
  var data = [
    {
      title: 'Mercedes',
      img: 'http://'
    }
  ]
  var postData = {
    pageGallery: data
  };
  var updates = {};
  updates['/app/cars/'] = postData;
  firebase.database().ref().update(updates);
  console.log('New car added');

}

And if I change and add the child:

firebase.database().ref().child('gallery').update(updates);

It does not do anything to do the data. Please can you help?

like image 583
TheBlackBenzKid Avatar asked Dec 02 '22 12:12

TheBlackBenzKid


1 Answers

See this blog post on the many reasons not use arrays in our Firebase Database. Read it now, I'll wait here...

Welcome back. Now that you know why your current approach will lead to a painful time, let's have a look at how you should model this data. The blog post already told you about push IDs, which are Firebase's massively scalable, offline-ready approach to array-like collections.

As our documentation on reading and writing lists of data explains, you can add items to a list by calling push().

So if this creates a car:

function addStore(){
  var rootRef = firebase.database().ref();
  var storesRef = rootRef.child('app/cars');
  var newStoreRef = storesRef.push();
  newStoreRef.set({
    name: "Cars",
    "pageId": "23",
    "storeURL": "/app/cars/gallery"
  });
}

Then to add an image to the gallery of that store:

var newCarRef = newStoreRef.child('gallery').push();
newCarRef.set({
  title: 'Mercedes',
  img: 'http://'
})

This will add a new car/image to the end of the gallery (creating the gallery if it doesn't exist yet).

like image 179
Frank van Puffelen Avatar answered Dec 04 '22 02:12

Frank van Puffelen