Firebase 如何判断哪些子体随on(“child”已更改)

Firebase 如何判断哪些子体随on(“child”已更改),firebase,Firebase,例如,我有以下数据库结构: / + users + 1 + items + -xxx: "hello" + 2 + items 然后, 如果将值“world”推送到“/users/1/items”,我可能会得到: {"items": {"-xxx": "hello", "-yyy": "world"}} 那么,如何判断哪一个发生了变化 我需要在“/users/$id/items”的每个引用上添加(“child_added”) 注意:我正试图在node.j

例如,我有以下数据库结构:

/ 
+ users
  + 1
    + items
      + -xxx: "hello"
  + 2
    + items
然后,

如果将值“world”推送到“/users/1/items”,我可能会得到:

{"items": {"-xxx": "hello", "-yyy": "world"}}
那么,如何判断哪一个发生了变化

我需要在“/users/$id/items”的每个引用上添加(“child_added”)


注意:我正试图在node.js中编写一个管理进程。

child\u changed事件只提供有关哪个直接子级已更改的信息。如果数据结构中较深的节点发生了更改,您将知道哪个直接子节点受到了影响,但不知道更改数据的完整路径。这是故意的

如果您想要精确地更新所更改的内容,那么应该将回调递归地附加到您关心的所有元素。这样,当项目发生更改时,您就知道触发回调的项目是什么。Firebase实际上针对这个用例进行了优化;附加大量回调(甚至数千次)应该可以正常工作。在幕后,Firebase将所有回调聚合在一起,只同步所需的最小数据集

因此,以您的示例为例,如果您希望在每次为任何用户添加新项目时收到警报,您可以执行以下操作:

var usersRef = new Firebase("https://mydb.firebaseio.com/users");
usersRef.on("child_added", function(userSnapshot) {
  userSnapshot.ref().child("items").on("child_added", function(itemSnapshot) 
    utils.debug(itemSnapshot.val());
  });
});
如果您与大量用户(数十万或数百万)一起工作,并且同步所有数据是不切实际的,那么还有另一种方法。与其让服务器直接侦听所有数据,不如让它侦听一个更改队列。然后,当客户端将项目添加到其项目列表中时,他们还可以将项目添加到此队列中,以便服务器能够意识到它

这就是客户端代码的外观:

var itemRef = new Firebase("https://mydb.firebaseio.com/users/MYID/items");
var serverEventQueue = new Firebase("https://mydb.firebaseio.com/serverEvents");
itemRef.push(newItem);
serverEventQueue.push(newItem);

然后,您可以让服务器监听该队列中添加的child_,并在事件进入时处理这些事件。

Andrew Lee给出了一个很好的答案,但我认为您应该尝试使用云功能。像这样的方法应该会奏效:

exports.getPath = functions.database.ref('/users/{id}/items/{itemId}')
.onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const original = event.data.val();
  console.log('user id', event.params.id);
  console.log('item id', event.params.itemId);
});

你的“我可能会得到”与你上面展示的结构不匹配;你有
“items”:{“1”:{“items”
,另外,你不能通过监听/users的“child_changed”来得到这个结果;你会得到这样的结果:
{“items:{……}}
我修正了“我可能会得到”的内容。谢谢。谢谢安德鲁。我了解了()handler有效。我现在使用第一种方法,有时可能使用第二种方法。注意!现在应该使用
userSnapshot.ref
而不是
userSnapshot.ref()
谢谢Andrew,我认为这是我需要走的方向,这篇文章非常有帮助。也谢谢Yernar。我将在不久的将来转向云函数,如果我成功,将在这里更新。通配符正是我需要的力量。@Yernar,“ref('/users/{id}/items/{itemId}”)结构是否适用于数据库引用api?(即非云函数api)@Bernatforet,我不这么认为,因为这是云功能的重点。它们有一些功能,你可以在你自己的后端使用。你是一个救世主,这个云功能拯救了我的一天。我需要区分哪个用户在db中更新了某个路径,它可以工作。@MbaiMburu投票支持我的答案:)我很高兴它工作了
exports.getPath = functions.database.ref('/users/{id}/items/{itemId}')
.onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const original = event.data.val();
  console.log('user id', event.params.id);
  console.log('item id', event.params.itemId);
});