Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Firebase云函数JavaScript-如何在一个函数中从不同的表中获取多个数据_Javascript_Firebase_Firebase Realtime Database_Google Cloud Functions - Fatal编程技术网

Firebase云函数JavaScript-如何在一个函数中从不同的表中获取多个数据

Firebase云函数JavaScript-如何在一个函数中从不同的表中获取多个数据,javascript,firebase,firebase-realtime-database,google-cloud-functions,Javascript,Firebase,Firebase Realtime Database,Google Cloud Functions,我在上面的Firebase DB中有这个结构 案例:当一个用户向另一个用户发送消息时,在customers/id/chats/chatid中,newMessage字段被更新为true 然后,我尝试从messages/chatid获取最后一条消息 通过chatid,我从客户处获得/id/chats/chatid 问题:我确实收到了关于客户的更新和数据,并发送了通知,但我需要最后一条消息,不知道怎么做 根本没有JavaScript经验。 我从客户那里获得的聊天id示例 _路径:“/customers

我在上面的Firebase DB中有这个结构

案例:当一个用户向另一个用户发送消息时,在customers/id/chats/chatid中,newMessage字段被更新为true

然后,我尝试从messages/chatid获取最后一条消息 通过chatid,我从客户处获得/id/chats/chatid

问题:我确实收到了关于客户的更新和数据,并发送了通知,但我需要最后一条消息,不知道怎么做 根本没有JavaScript经验。 我从客户那里获得的聊天id示例 _路径:“/customers/m6QNo7w8X8PjnBzUv3EgQiTQUD12”, _数据: {chats:{'-LCPNG9rLzAR5OSfrclG':[Object]}

const functions=require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotif=functions.database.ref('/customers/{id}/chats/{id}/')。onUpdate((事件)=>{
const user=event.data.val();
console.log('Event data:',Event.data);
//在这里,我想使用聊天ID获取消息中的消息。
//获取最后一条消息并发送通知。
//这在更新newMessage字段时起作用。
//但是,我需要从另一个表中获取消息内容。
变量myoptions={
优先级:“高”,
寿命:60*60*24
};
//应通过最后一条消息填写的通知数据。
常数notifData={
“通知”:
{
“身体”:“伟大的比赛!”,
“头衔”:“葡萄牙对丹麦”,
“声音”:“默认值”
} 
}
admin.messaging().sendToDevice(user.fcm.token、notifData、myoptions)
.然后(功能(响应){
console.log('已成功发送消息:',响应);
})
.catch(函数(错误){
console.log('发送消息时出错:',错误);
});
返回“”

})
为了获取最后一条消息,您必须在Firebase数据库中存储某种时间戳(例如使用Javascript)


然后,您将获得所有相关的消息,使用函数对它们进行排序,并仅使用最新的消息


您可以结合使用三个Firebase查询函数:、和。

为了获取最后一条消息,您必须在Firebase数据库中存储某种时间戳(例如在Javascript中使用)


然后,您将获得所有相关的消息,使用函数对它们进行排序,并仅使用最新的消息


您可以结合使用三个Firebase查询函数:,和。

执行以下操作。请参阅代码中的注释和结尾的注释

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{chatId}').onUpdate((change, context) => {

    //const afterData = change.after.val();  //I don't think you need this data (i.e. newMessage: true)
    const chatId = context.params.chatId; //the value of {chatId} in  '/customers/{id}/chats/{chatId}/' that you passed as parameter of the ref

    //You query the database at the messages/chatID location and return the promise returned by the once() method        
    return admin.database().ref('/messages/' + chatId).once('value').then(snapshot => {

        //You get here the result of the query to messagges/chatId in the DataSnapshot
        const messageContent = snapshot.val().lastMessage;


        var myoptions = {
           priority: "high",
           timeToLive: 60 * 60 * 24
        };

        // Notification data which supposed to be filled via last message. 
       const notifData = {
        "notification":
        {
          "body" : messageContent,  //I guess you want to use the message content here??
          "title" : "Portugal vs. Denmark",
          "sound": "default"
        } 
       };


       return admin.messaging().sendToDevice(user.fcm.token, notifData, myoptions);
  )
  .catch(function(error) {
        console.log('Error sending message:', error);
  });

});
请注意,我已将代码从

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{id}/').onUpdate((event) => {

后者是几周前发布的云函数v1.+的新语法

您应该更新云函数版本,如下所示:

npm install firebase-functions@latest --save
npm install firebase-admin@5.11.0 --save

有关更多信息,请参阅此文档项:

按如下操作。请参阅代码中的注释和结尾处的备注

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{chatId}').onUpdate((change, context) => {

    //const afterData = change.after.val();  //I don't think you need this data (i.e. newMessage: true)
    const chatId = context.params.chatId; //the value of {chatId} in  '/customers/{id}/chats/{chatId}/' that you passed as parameter of the ref

    //You query the database at the messages/chatID location and return the promise returned by the once() method        
    return admin.database().ref('/messages/' + chatId).once('value').then(snapshot => {

        //You get here the result of the query to messagges/chatId in the DataSnapshot
        const messageContent = snapshot.val().lastMessage;


        var myoptions = {
           priority: "high",
           timeToLive: 60 * 60 * 24
        };

        // Notification data which supposed to be filled via last message. 
       const notifData = {
        "notification":
        {
          "body" : messageContent,  //I guess you want to use the message content here??
          "title" : "Portugal vs. Denmark",
          "sound": "default"
        } 
       };


       return admin.messaging().sendToDevice(user.fcm.token, notifData, myoptions);
  )
  .catch(function(error) {
        console.log('Error sending message:', error);
  });

});
请注意,我已将代码从

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{id}/').onUpdate((event) => {

后者是几周前发布的云函数v1.+的新语法

您应该更新云函数版本,如下所示:

npm install firebase-functions@latest --save
npm install firebase-admin@5.11.0 --save

有关更多信息,请参阅此文档项:

您正在成功更新“customers/uid/chats/chat”分支,这说明您拥有聊天id/uid。您所做的只是获取“messages/chat”并阅读它。由于您拥有聊天id,因此有一个
.Promise。所有
方法都在这里工作。类似于:

    var promises = [writeChat(),readChat()];

    Promise.all(promises).then(function (result) {
        chat = result[1]; //result[1].val()
    }).catch(function (error) {
        console.error("Error adding document: ", error);
    });

    function readChat() {
        return new Promise(function (resolve, reject) {
          var userId = firebase.auth().currentUser.uid;
          return firebase.database().ref('/users/' + userId).once('value').then(function(snap) {
             resolve (snap)
             // ...
          }).catch(function (error) {
            reject(error);
          });
       });
    }

您正在成功更新“customers/uid/chats/chat”分支的事实表明您拥有聊天id/uid。您所做的只是获取“messages/chat”并阅读它。由于您拥有聊天id,因此有一个
.Promise。所有
方法都在这里起作用。类似于:

    var promises = [writeChat(),readChat()];

    Promise.all(promises).then(function (result) {
        chat = result[1]; //result[1].val()
    }).catch(function (error) {
        console.error("Error adding document: ", error);
    });

    function readChat() {
        return new Promise(function (resolve, reject) {
          var userId = firebase.auth().currentUser.uid;
          return firebase.database().ref('/users/' + userId).once('value').then(function(snap) {
             resolve (snap)
             // ...
          }).catch(function (error) {
            reject(error);
          });
       });
    }

工作做得很好,我只修改了一些语法错误。@selcuk很高兴知道我可以帮助你!顺便说一句,既然我的答案解决了你的问题,你可以接受它,除了你的投票,请看谢谢!!工作做得很好,我只修改了一些语法错误。@selcuk很高兴知道我可以帮助你!顺便说一句,既然我的答案解决了你的问题,你可以接受接受它,除了你的投票,见谢谢!!