从firebase数据库中删除项目

时间:2018-04-11 19:50:22

标签: firebase firebase-realtime-database ionic3 angularfire2

我的firebase中有一个餐馆书签列表,但我不知道如何删除我数据库中的特定餐馆。

所以我有函数unfavorite(favorite),我把最喜欢的餐馆作为参数传递给我。到这里,我想将这个参数id传递给查询,以便从数据库中删除:

this.afDb.list(`bookmarks/${user.uid}/restaurant/${favorite.restaurant.id})`).remove();

这是我的数据库列表的屏幕截图:

enter image description here

如何从书签列表中删除该特定餐厅?

1 个答案:

答案 0 :(得分:3)

首先需要向数据库中添加".indexOn": ["id"]规则,如下所示:

"bookmarks": {
  "$user_id": {
    // normal reads and write rules here
  },
  ".indexOn": ["id"]

此步骤对于firebase数据库是必需的,否则您将无法使用orderByChild()equalTo()方法。

然后,在你有删除功能的地方,你想改为使用:

exampleRef = yourDb.ref("bookmarks/${user.uid}"); //this is just to simplify your reference a bit 
exampleRef.orderByChild('id').equalTo(theDeleteIDhere).once('value').then(snapshot => {
    snapshot.forEach((restaurant) => {
        restaurant.ref.remove();
    });
}); //this is a Promise that you can modify to return "true" if successful for example 

我提供的示例就是我以前做过的方式(即我更喜欢使用promises;因此then()因为这使得更容易在角度服务中返回该承诺,这允许我检查是否请求成功了)。你可以使用任何变体,只要你有“indexOn”规则并使用firebase提供的任何“排序”方法here

方法2 当我写这篇文章的时候,我完全瞥了一眼像这样映射餐馆的能力:

让我们说你的项目已经列出了那些餐馆。因此,您可以将每个餐馆的自动生成的ID保存到变量或地图中:

restaurants; // this is a map like this <your-identifier:autoID>

然后您可以轻松地致电:

exampleRef.child(restaurants[yourIdentifier]).remove();
相关问题