Javascript 如何在 Firebase Web 应用中插入新的子数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39976818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:06:45  来源:igfitidea点击:

How to insert new child data in Firebase web app?

javascriptfirebasefirebase-realtime-database

提问by TheBlackBenzKid

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:

我正在构建一个简单的汽车数据库应用程序。当用户添加一辆新车时,它会为图库创建以下带有空白字段的 JSON 数据:

{
    "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 Ferrariit 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.

现在我想在应用程序中做的是,如果用户添加了一个新的画廊图片,它应该在最后一个画廊图片之后添加新的孩子。所以在法拉利之后它应该插入一个新对象。我似乎无法做到这一点,因为每个教程都会导致死胡同,而且官方 Google 文档指定set()将替换所有数据,因此如果您使用update()它,它将添加,在这种情况下它不会添加。

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?

它不做任何事情来做数据。请问你能帮忙吗?

回答by Frank van Puffelen

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

有关不在 Firebase 数据库中使用数组的多种原因,请参阅此博客文章。读吧,我在这里等……

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

欢迎回来。现在您知道为什么您当前的方法会导致痛苦的时间,让我们来看看您应该如何对这些数据进行建模。博文已经介绍了推送 ID,这是 Firebase 对类数组集合的大规模可扩展、离线就绪的方法。

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

正如我们关于读取和写入数据列表的文档所解释的那样,您可以通过调用 将项目添加到列表中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).

这将在图库的末尾添加一个新的汽车/图像(如果尚不存在,则创建图库)。

回答by Hitesh Sahu

If somebody wants it With Error Handling :

如果有人想要它带有错误处理:

          var rootRef = firebase.database().ref();
          var storesRef = rootRef.child('Lorelle/Visitors');
          var newStoreRef = storesRef.push();
          newStoreRef.set($scope.CarModal,
            function(error) {
              //NOTE: this completion has a bug, I need to fix.
              if (error) {
                   console.log("Data could not be saved." + error);
                   Materialize.toast('Error: Failed to Submit' + error, 2000);
              } else {
                 console.log("Data saved successfully.");
                 Materialize.toast('Data Submitted, Thank You.', 2000);

                   }
                });
             }