Firebase函数如何从Firebase数据库获取布尔值

时间:2018-09-03 13:55:30

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

我在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);

the records of firebase function

1 个答案:

答案 0 :(得分:0)

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

上面的代码即可