如何从服务器端上的Firebase数据库检索最后创建的对象

时间:2023-01-14 11:26:48

I'm new to Firebase cloud functions so sorry if this is pretty straight forward. I'm trying to receive the latest pushed object in my database. Unfortunately this code returns every object that already was pushed in the database at '/customers'. I already tried .onCreate but that didn't do anything at all.

我刚接触过Firebase云函数,不好意思,这很直接。我正在尝试接收数据库中最新的push对象。不幸的是,这段代码返回数据库中“/customers”中已被推送的每个对象。我已经试过。oncreate了,但什么都没做。

exports.newCustomer = functions.database.ref('/customers/').onWrite(event => {
  console.log(event.data.val());
});

如何从服务器端上的Firebase数据库检索最后创建的对象

1 个解决方案

#1


2  

That onWrite event should only capture new data. However maybe you should more specific like this:

onWrite事件应该只捕获新数据。但是,也许你应该更具体一些:

exports.newCustomer = functions.database.ref('/customers/{randomID}').onWrite(event => {
  console.log(event.data.val()); //here is the data that is added
  console.log(event.params.randomID); // random ID
  console.log(event.data.val().firstName); //change firstName to anything you added.
});

This will capture any write event to /customers/XXX/XXX/

这将捕获任何写给/客户/XXX/XXX的写事件

#1


2  

That onWrite event should only capture new data. However maybe you should more specific like this:

onWrite事件应该只捕获新数据。但是,也许你应该更具体一些:

exports.newCustomer = functions.database.ref('/customers/{randomID}').onWrite(event => {
  console.log(event.data.val()); //here is the data that is added
  console.log(event.params.randomID); // random ID
  console.log(event.data.val().firstName); //change firstName to anything you added.
});

This will capture any write event to /customers/XXX/XXX/

这将捕获任何写给/客户/XXX/XXX的写事件