【问题标题】:Checking the value of a node in firebase and adding to datab检查firebase中节点的值并添加到数据
【发布时间】:2020-01-11 16:44:15
【问题描述】:

我需要编写代码来查看notifications/notifications_switch 的值。如果这个键的值为 1,我需要向 test_manav 节点添加一个新节点。我很困惑是否应该使用我当前编写的代码(第二个 sn-p)来完成此操作,通过使用 ref.key,然后检查键的值,或者我是否应该使用:

ref.on('value', function(snapshot){
   if(snapshot.val()==1){
exports.scheduledFunction = functions.pubsub.schedule('every 1000 minutes').onRun((context) => {
  var db = admin.database().ref().child('test_manav');
  var ref = admin.database().ref('/notifications/notifications_switch');
  var key = ref.key;
  if(key==1){
      return db.update({
        time: admin.database.ServerValue.TIMESTAMP,
        test: 'Hello Manav'
      });
    }
});

【问题讨论】:

  • 您是否只需要执行一次此更新,或者您想持续收听notifications/notifications_switch 的值?
  • @RenaudTarnec 我必须每 1000 分钟听一次值,这就是我使用 pubsub 功能的原因

标签: node.js firebase firebase-realtime-database google-cloud-functions firebase-admin


【解决方案1】:

【讨论】:

  • 读取数据库链接失效了,请问您还有其他链接吗?
  • 和第二个链接一样,只是url中没有命名锚。
【解决方案2】:

以下应该可以解决问题:

exports.scheduledFunction = functions.pubsub.schedule('every 1000 minutes').onRun((context) => {
    const db = admin.database();
    const targetRef = db.ref('test_manav');
    const switchRef = db.ref('notifications_switch');

    return switchRef.once('value')   // <-- See the return here
        .then(dataSnapshot => {
            if (dataSnapshot.val() === 1) {
                return targetRef.update({     // <-- See the return here
                    time: admin.database.ServerValue.TIMESTAMP,
                    test: 'Hello Manav'
                });
            } else {
                return null;
            }
        });
});

正如 Doug 在他的回答中所解释的那样:

  1. 您应该使用once() 方法;
  2. 当异步任务通过返回 Promise 链完成时,您必须返回一个 Promise。

【讨论】:

    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2021-11-19
    • 2018-06-30
    • 2021-01-13
    • 2019-02-24
    相关资源
    最近更新 更多