【问题标题】:How to reach document name in angularfire, if I know record?如果我知道记录,如何在 angularfire 中获取文档名称?
【发布时间】:2014-10-31 05:35:11
【问题描述】:

我有一些记录,比如

{
  "posts" : {
    "1" : {
      "text" : "sometext",
      "title" : "test"
    }
  },
  "user_posts" : {
      "-J_ZT9vZJ4CcXh3PuiwR" : "1"
    }
}

如何使用记录“1”获得“user_posts”中的文档名称? 我需要删除这个。这就是我正在做的:

$firebase(ref.child('user_posts')).$remove($indexFor(post.$id));
//post.$id is a id os post on posts, by using ng-repeat...

但我无法移除。 console.log() 总是返回 -1。我觉得我做错了什么......

【问题讨论】:

    标签: json angularjs firebase behavior angularfire


    【解决方案1】:

    更新

    我最初误解了你的问题。我现在了解到,当从 posts 中删除节点 1 时,您想从 user_posts 中删除节点 "-J_ZT9vZJ4CcXh3PuiwR"

    您不能为此使用$indexFor。由于您要匹配的对象位于两个不同的集合中,因此posts -> 1 不可能与user posts -> -J_ZT9vZJ4CcXh3PuiwR 相同。

    相反,您必须想出另一种方法来匹配它们。最简单的可能是将帖子ID设置为user_posts上的优先级:

    userPostsRef.push().setWithPriority(1, 1);
    

    所以这会将值和优先级都设置为 1。

    然后您可以使用查询按优先级找到正确的条目:

    userPostsRef.startAt(1).endAt(1).once('child_added', function(snapshot) {
        snapshot.ref().remove();
    });
    

    这使用 Firebase 的标准 Web/JavaScript API,它与 AngularFire 互操作。如果您希望在 AngularFire 中看到它,则必须自己翻译。

    原答案

    要使用 $firebase 使用 AngularFire 删除项目,您只需传入要删除的节点的名称:

    $firebase(ref.child('user_posts')).$remove(post.$id);
    

    见:https://www.firebase.com/docs/web/libraries/angular/guide.html#section-basics

    【讨论】:

    • post.$id 它是“posts”节点的一个节点,而不是“user_posts”。这就是我要问的 - 如何通过知道该节点中的记录来获得帖子的名称。
    • 啊,好的,我现在明白了。您似乎误解了 $indexFor 的作用:“获取密钥并在数组中找到关联的记录”。您正在传递post.$id,即1。但这不是-J_ZT9vZJ4CcXh3PuiwR 的记录,所以它不会找到匹配项,因此返回-1。我给你写一个例子。
    • 实际上在 'post' 中生成了一个带有节点名称的帖子元数据,相当于 'User_posts' 中的记录。我只是将帖子中的名称重命名为 1,以便更清楚地说明这一点。但他们每次都匹配。
    猜你喜欢
    • 2019-01-19
    • 2022-01-17
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多