【问题标题】:Update value once write completes in Cloud Function在 Cloud Function 中完成写入后更新值
【发布时间】:2017-08-21 15:44:09
【问题描述】:

我试图在写入完成后更新一个值(在云函数中),但它不起作用(我确信这是一个愚蠢的简单问题)。代码如下:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firebase = require('firebase');

 admin.initializeApp(functions.config().firebase);
 exports.createMessage = functions.https.onRequest((request, response) => {
        const json = JSON.parse(request.query.json); // == "{'start':0, 'end':0}"
        json.start = firebase.database.ServerValue.TIMESTAMP;
        admin.database().ref('/messages/').push(json).then(snapshot => {

            //Here is the problem. Whatever I try here it won't work to retrieve the value.
            //So, how to I get the "start" value, which has been written to the DB (TIMESTAMP value)?
            var startValue = snapshot.ref.child('start').val();

            snapshot.ref.update({ end: (startValue + 85800000) }).then(snapshot2=>{
                response.redirect(303, snapshot.ref);
            });
        });
 });

是我使用 admin.database() 的问题吗?

【问题讨论】:

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


    【解决方案1】:

    这段代码:

    var startValue = snapshot.ref.child('start').val();
    

    实际上并不检索任何值。查看DataSnapshot 的文档。使用child() 直接访问该快照 - 您不需要ref。也许这就是你的意思?

    var startValue = snapshot.child('start').val();
    

    【讨论】:

    • 谢谢,但这不起作用。事实上,我根本无法在快照参考上使用任何方法。错误日志:“TypeError:snapshot.child 不是函数”。我“解决”了我的问题,有关详细信息,请参阅我的答案。
    【解决方案2】:

    我不确定 Firebase 中是否存在错误,或者我是否使用错误,但如果我尝试调用 snapshot-reference 上的任何方法,我只会收到一条错误消息:TypeError: snapshot.xxx is not a function where xxx 是我尝试使用的函数名(例如:child(...)、forEach(...) 等)。

    但是,以下似乎解决了snapshot 的问题:

    admin.database().ref('/messages/').push(json).once('value').then(snapshot => {
    

    代替:

    admin.database().ref('/messages/').push(json).then(snapshot => {
    

    我的有根据的猜测是then-promise,对于push-函数会返回一些错误的snapshot,因为似乎唯一有效的是snapshot.key

    另外,如果我没记错的话,我的解决方案现在不是读取两次,而不是读取一次吗?因为push 将写入然后(假设)读取并返回写入的值,然后我用once(value) 再次读取它。

    有人对这个问题有任何进一步的见解吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2023-01-07
      • 2018-06-06
      相关资源
      最近更新 更多