1

下面的代码来直Firebase Functions getting started tutorial为什么数据库快照未定义Firebase管理节点Js?

const functions = require('firebase-functions'); 
// The Firebase Admin SDK to access the Firebase Realtime Database. 
const admin = require('firebase-admin'); 

admin.initializeApp(functions.config().firebase); 

exports.addMessage = functions.https.onRequest((req, res) => { 

    let userid = 'afewfaewf'; 
    let dummyJson = {key: 'value'}; 
    let dbPath = '/' + userid; 
    admin.database().ref(dbPath).update({dummy: dummyJson}).then(snapshot => { 
    console.log('finished writing to Firebase database '); 
    console.log(snapshot === undefined); 
    res.redirect(303, snapshot.ref); 
    }); 
}); 

这里是在本地运行它的全部输出:

❯ firebase serve --only functions 

=== Serving from '/Users/eric/AndroidStudioProjects/XXX/firebase-functions'... 

i functions: Preparing to emulate HTTPS functions. Support for other event types coming soon. 
Warning: You're using Node.js v7.7.1 but Google Cloud Functions only supports v6.9.1. 
Server#addProtoService is deprecated. Use addService instead 
✔ functions: addMessage: http://localhost:5002/xxx/us-central1/addMessage 
info: User function triggered, starting execution 
info: finished writing to Firebase database 
info: true 
error: (node:11005) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'ref' of undefined 
(node:11005) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

而关于云:

11:44:06.290 PM 
warning 
addMessage 
TypeError: Cannot read property 'ref' of undefined at admin.database.ref.update.then.snapshot (/user_code/index.js:32:31) at process._tickDomainCallback (internal/process/next_tick.js:129:7) 
TypeError: Cannot read property 'ref' of undefined 
    at admin.database.ref.update.then.snapshot (/user_code/index.js:32:31) 
    at process._tickDomainCallback (internal/process/next_tick.js:129:7) 
11:44:06.289 PM 
warning 
addMessage 
Unhandled rejection 
11:44:06.288 PM 
info  
addMessage 
true 
11:44:06.283 PM 
info  
addMessage 
finished writing to Firebase database 
11:44:05.322 PM 
outlined_flag 
addMessage 
Function execution started 
+1

因为这些代码是错误的。 'update'返回一个解析为'void'(即'undefined')的promise - 而不是'Snapshot'。 – cartant

+0

https://firebase.google.com/docs/reference/node/firebase.database.Reference#update – cartant

+0

谢谢@cartant,你介意把它放在答案中,以便我可以接受它吗?顺便说一句,你能否详细说明如何使用“承诺”,是否需要某种异步回调来获得结果,无论我的更新是否失败或最终成功? – ericn

回答

0

感谢@cartan指着我向正确的方向

The原始示例从Firebase数据库中“读取”,以便返回snapshop值

另一方面,我的代码尝试“写入”Firebase数据库,但没有返回值,而是返回一个回调。
我已经改变了我的代码以下,一切完美的作品如预期:

admin.database().ref(dbPath).update({dummy: dummyJson}, function (err) { 
    console.log("done with error " + err); 
    res.status(200).send("success"); 
    }); 
相关问题