简体   繁体   English

如何从 Cloud Functions 访问和操作 Firebase 数据库?

[英]How can I reach and manipulate Firebase Database from Cloud Functions?

I am working on sending dynamic notification to user.我正在努力向用户发送动态通知。 Therefore, I am dealing with the Firebase Cloud Functions.因此,我正在处理 Firebase Cloud Functions。 Here is my question: How can I reach database in the cloud functions side?这是我的问题:如何在云功能端访问数据库?

Here is my codes:这是我的代码:

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




// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

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


var newData;



//exports.myTrigger= functions.firestore.document().




exports.notificationTrigger = functions.firestore.document(`notifications/{notificationId}`).onCreate(async (snapshot, context) => {


    if (snapshot.empty) {
        console.log('No Devices');
        return;
    }
  var notificationData = snapshot.data();
  // notificationData.email;
  console.log(`Data  is : ${notificationData.email}`);


      admin.database().ref(`users/${notificationData.email}/deviceToken`).then((snapshot) => {
            var token = snapshot.data();
            console.log('token',token)
            return 1;
        }).catch(err => {
            console.error(err);

        }); 





    var tokens = [
        `${token.deviceToken}`
    ];



    var payload = {
        notification: {
            title: `Yeni Eklenen Değerin Maili : ${notificationData.email}`,
            body: 'hüsen',
            sound: 'default',
        },
        data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK',
            Messages:'Baba Mesajı from otomatik fonksiyon'
        },
    };

    try {
        const response = await admin.messaging().sendToDevice(tokens, payload);
        console.log('Notification sent successfully');
    } catch (err) {
        console.log(err);
    }
});  

As you can see, Firstly, I want to take email from nofications collection, then using that email, I want to search user which is using that email, After that, I want to take user deviceToken.如您所见,首先,我想从 nofications 集合中获取 email,然后使用该 email,我想搜索正在使用该 email 的用户,之后,我想获取用户 deviceToken。

I tried so much things about syntax but I did not get any result from them:/我尝试了很多关于语法的东西,但我没有从中得到任何结果:/

Likewise, I took some kind of errors:同样,我犯了一些错误:

Here you can see the errors:在这里你可以看到错误:

  • Reference.child failed: First argument was an invalid path = "users/patientaccount@gmail.com/deviceToken". Reference.child 失败:第一个参数是无效路径 =“users/patientaccount@gmail.com/deviceToken”。 Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" at validatePathString (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1667:15) at validateRootPathString (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1679:5) at Reference.child (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:13843:17) at Database.ref (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:15097:48) at exports.notificationTrigger.functions.firestore.document.onCreate (/srv/index.js:37:24) at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23) at /worker/worker.js:825:24 at at process._tickDomainCallback (internal/process/next_tick.js:229:7)路径必须是非空字符串,并且在 validatePathString (/srv/node_modules/@firebase/database/dist/index.node .cjs.js:1667:15) 在 validateRootPathString (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1679:5) 在 Reference.child (/srv/node_modules/@firebase/database) /dist/index.node.cjs.js:13843:17) 在 Database.ref (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:15097:48) 在 exports.notificationTrigger.functions .firestore.document.onCreate (/srv/index.js:37:24) 在 cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23) 在 /worker/worker.js: 825:24 在 process._tickDomainCallback(内部/process/next_tick.js:229:7)

The error message is telling you what went wrong:错误消息告诉您出了什么问题:

Reference.child failed: First argument was an invalid path = "users/patientaccount@gmail.com/deviceToken". Reference.child 失败:第一个参数是无效路径 =“users/patientaccount@gmail.com/deviceToken”。 Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"路径必须是非空字符串,不能包含“.”、“#”、“$”、“[”或“]”

The path that includes the email address has an invalid character .包含 email 地址的路径包含无效字符. . .

If you want to store per-user data, you should instead use the user account's unique ID.如果您想存储每个用户的数据,您应该使用用户帐户的唯一 ID。 Email addresses do not make very good unique identifier for a variety of reasons.由于各种原因,Email 地址并不是很好的唯一标识符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用云函数从我的 Firebase 实时数据库中 database.ref 正在侦听的节点内部获取数据? - How can I fetch data from inside a node which the database.ref is listening to in my Firebase real-time database using cloud functions? 如何将 Firebase 参数化配置与 Typescript 一起用于 Cloud Functions? - How can I use Firebase Parameterized configuration with Typescript for Cloud Functions? Firebase RemoteConfig 是否可以从云功能访问 - Can Firebase RemoteConfig be accessed from cloud functions 如何使用 firebase 云消息和云功能设置推送通知? - How can I go about setting up push notifications using firebase cloud messaging and cloud functions? 如何从云端访问 firebase 自定义声明 function - How can I access firebase custom claims from a cloud function 部署 Firebase 云函数时如何修复命令行错误 supportedNodeVersions? - How can I fix command line error supportedNodeVersions when deploying Firebase cloud functions? 与 firebase 云函数中的 firebase firestore 交互 - Interacting with firebase firestore from firebase cloud functions 如何从云函数中的请求中获取参数? 火力地堡 - How to get parameters from request in cloud functions? Firebase 如何在 Firebase Cloud Functions 中对 npm 模块使用 `import`? - How do I use `import` for npm modules in Firebase Cloud Functions? 如何在 Cloud Functions for Firebase 中获取服务器时间戳? - How do I get the server timestamp in Cloud Functions for Firebase?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM