我正在尝试在写入完成后更新一个值(在云函数中)但它不会工作(我确定这是一个非常简单的问题)。代码如下:
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()?
答案 0 :(得分:2)
此代码:
var startValue = snapshot.ref.child('start').val();
实际上并未检索任何值。看一下DataSnapshot的文档。使用child()直接覆盖该快照 - 您不需要ref
。也许这就是你的意思?
var startValue = snapshot.child('start').val();
答案 1 :(得分:0)
我不确定Firebase中是否存在错误,或者我是否使用了错误,但如果我尝试调用snapshot
上的任何方法 - 引用我只会得到一个错误说:TypeError: snapshot.xxx is not a function
其中xxx是我尝试使用的函数名称(例如:child(...),forEach(...)等)。
但是,以下似乎解决了snapshot
:
admin.database().ref('/messages/').push(json).once('value').then(snapshot => {
而不是:
admin.database().ref('/messages/').push(json).then(snapshot => {
我的 un 有根据的猜测是then
- 承诺,对于push
- 函数会返回一些有问题的snapshot
,因为唯一似乎有用的东西是snapshot.key
。
另外,如果我没有弄错,我的解决方案现在不进行两次读取吗?由于push
会写入然后(据说)读取并返回写入的值,然后我再次使用once(value)
读取它。
有没有人对此问题有任何进一步的见解?