【问题标题】:Firebase functions how to get a boolean value from Firebase DatabaseFirebase 函数如何从 Firebase 数据库中获取布尔值
【发布时间】:2018-09-03 13:55:30
【问题描述】:

我在 Firebase 的函数中有一个 node.js 中的代码,我只想知道如何在“Users”类中的每个用户中获取变量“read”的布尔值。

我的代码:

let functions = require('firebase-functions');

let admin = require('firebase-admin');

admin.initializeApp();

exports.sendNotificationNewChat = functions.database.ref('/Usuarios/{usuarioId}/Chats/{chatsId}').onWrite((change, context) => {

    //get the userId of the person receiving the notification because we need to get their token
//const receiverId = context.params.userId;
//console.log("receiverId: ", receiverId);
/*
    // Only edit data when it is first created.
      if (change.before.exists()) {
        return null;
      }*/
      // Exit when the data is deleted.
      if (!change.after.exists()) {
        return null;
      }

    if (!change.after.exists()) {
        return null;
    }
    //te escribe el json de el mensaje nuevo
    const afterData = change.after.val();
    console.log("afterData: ", afterData);

  //  const readChat = afterData.read;
   // console.log("readChat: ", readChat);


//get the user id of the person who sent the message
    const senderId = context.params.usuarioId;
    console.log("senderId: ", senderId);

//get the user id of the person who sent the message
    const receiverId = afterData.IdOtherUser;
    console.log("receiverId: ", receiverId);


//get the message
    const nameAd = afterData.nameAd;
    console.log("nameAd: ", nameAd);


//get the message
    const ChatId = context.params.chatsId;
    console.log("ChatId: ", ChatId);

    /*
    //get the message id. We'll be sending this in the payload
    const messageId = context.params.messageId;
    console.log("messageId: ", messageId);
    */
    return admin.database().ref("/Usuarios/"+senderId+"/Chats/"+ChatId).once('value').then(snap => {
        const readChat = snap.child("read").val();
       // if (readChat) return null
        console.log("readChat: ", readChat);



//query the users node and get the name of the user who sent the message
    return admin.database().ref("/Usuarios/" + senderId).once('value').then(snap => {
        const senderName = snap.child("name").val();
        console.log("senderName: ", senderName);

//get the token of the user receiving the message
        return admin.database().ref("/Usuarios/" + receiverId).once('value').then(snap => {

            const receiverName = snap.child("name").val();
            console.log("receiverName: ", receiverName);

            const token = snap.child("token").val();
            console.log("token: ", token);

//we have everything we need
//Build the message payload and send the message
            console.log("Construction the notification message.");
            const payload = {
                data: {
                    data_type: "direct_message",
                    title: "Nueva conversación de " + senderName,
                    message: "Selecciona para ver los mensajes",
                }
            };

            return admin.messaging().sendToDevice(token, payload)
                .then(function(response) {
                    return console.log("Successfully sent message:", response);
                })
                .catch(function(error) {
                    return console.log("Error sending message:", error);
                });
        });
    });
});
});

我使用这部分代码来获取读取值,但 firebase 函数的记录总是告诉我它得到空值
从“读取”中获取布尔值的部分代码:

admin.database().ref("/Usuarios/"+senderId+"/Chats/"+ChatId).once('value').then(snap => {
            const readChat = snap.child("read").val();
           // if (readChat) return null
            console.log("readChat: ", readChat);

【问题讨论】:

  • 能否请您添加数据库的确切结构,如果可能的话,导出数据(当您在 RTDB 模块上时,请使用 Firebase 控制台右上角的三个点按钮)

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


【解决方案1】:

snap.val() 将返回一个对象,因此您可以对象并将其存储在变量中并尝试访问它或尝试如下所示

admin.database().ref("/Usuarios/"+senderId+"/Chats/"+ChatId).once('value')           
.then(snap => {              
        if(snap.numChildren() === 0) // check for no data available              
        snap.child("read").val(); // instead of this line write like below
        const readChat =  **snap.val()[read];** or **snap.val().read**
       // if (readChat) return null
        console.log("readChat: ", readChat);
})

// 考虑到你的结构

---user
-----senderId
--------Chats
-----------ChatId
---------------read: true

上面的代码就可以了

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 2018-09-10
    • 1970-01-01
    • 2021-04-09
    • 2019-11-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多