简体   繁体   English

Firebase 使用 orderByChild() 删除数据?

[英]Firebase delete data with orderByChild() with a key?

When removing an item from my RTDB, my intention is to clean up user's likes if the item they like got removed.从我的 RTDB 中删除项目时,我的目的是清理用户喜欢的项目,如果他们喜欢的项目被删除。

With my data structure like so:我的数据结构是这样的:

在此处输入图像描述

I am attempting to remove the nodes like this:我正在尝试删除这样的节点:

  const updates = {};

  //WORKS
  updates[`/strains/${title}/`] = null;
  updates[`/strainsMin/${title}/`] = null;

firebase
  .database()
  .ref('reviews')
  .orderByChild('s')
  .equalTo(title)
  .once('value', snapshot => {
    console.log(snapshot.val())
    snapshot.forEach(child => {
      console.log(child.key)
      //WORKS
      updates[`/reviews/${child.key}`] = null;
    });
  })
  .then(() => {
    firebase
    .database()
    .ref('userLikedStrains')
    .orderByChild(title)
    .equalTo(title)
    .once('value', snapshot => {
      console.log(snapshot.val() + 'likeylikeyyy')
      snapshot.forEach(child => {
        console.log(child.key)
        //DOESNT WORK
        updates[`/userLikedStrains/${child.key}/${title}`] = null;
      });
      firebase
      .database()
      .ref()
      .update(updates);
    })

For some reason this doesn't work.由于某种原因,这不起作用。 Is it because I am targeting a key (which is still a child?..)是不是因为我的目标是一把钥匙(它仍然是一个孩子?..)

I appreciate any help with this.我很感激这方面的任何帮助。 Cheers.干杯。

The code you shared is not writing anything back to the database yet.您共享的代码尚未将任何内容写回数据库。 For that you need to call update after the loop.为此,您需要在循环后调用update

Something like:就像是:

let ref = firebase
    .database()
    .ref('userLikedStrains');

ref.orderByChild(title)
    .equalTo(title)
    .once('value', snapshot => {
      console.log(snapshot.val())
      snapshot.forEach(child => {
        console.log(child.key)
        updates[`/userLikedStrains/${child.key}/${title}`] = null;
      });
      ref.update(updates);
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM