检测一个 ref 的变化并写入另一个 Firebase Cloud

Detect changes in one ref and write in another Firebase Cloud

我正在尝试在我的应用程序中使用 Firebase Cloud Functions,使用此代码在创建 2 小时后删除数据。

exports.deleteOldItems = functions.database.ref('/Rooms/{pushId}')
.onWrite(event => {
  var ref = event.data.ref.parent; // reference to the items
  var now = Date.now();
  var cutoff = now - 2 * 60 * 60 * 1000;
  var oldItemsQuery = ref.orderByChild('timestampCreated/timestamp').endAt(cutoff);
  return oldItemsQuery.once('value', function(snapshot) {
    // create a map with all children that need to be removed
    var updates = {};
    snapshot.forEach(function(child) {
      updates[child.key] = null
    });
    // execute all updates in one go and return the result to end the function
    return ref.update(updates);
  });
});

这行得通。现在我想在另一个ref中写入(例如:/Users/{userID}/)每次删除数据。此致

根据您希望以当前用户还是管理员身份更新到 运行,您可以使用 event.data.refevent.data.adminRef 并从那里开始工作:

exports.deleteOldItems = functions.database.ref('/Rooms/{pushId}')
.onWrite(event => {
  ...
  var ref = event.data.ref.root;
  return ref.child("/Users/123").set("New value");
});

版本 1.0 发生了变化,adminRef 已弃用,您应该只使用 ref 进行管理员访问,event 已被 snapshotcontext,请看这里:cloud functions documentation 1.0 API changes

Frank 的示例变为:

exports.deleteOldItems = functions.database.ref('/Rooms/{pushId}')
.onWrite((snapshot,context) => {
  ...
  var ref = snapshot.ref.root;
  return ref.child("/Users/123").set("New value");
});