打印变量

时间:2018-03-09 07:34:32

标签: node.js google-cloud-firestore

我正在从firestore中检索数据以获取数据。我将数据存储到变量中。我需要在代码的另一部分中使用该变量。当我使用它时它会显示一个未定义的代码。我检索了用户详细信息并发送通知。在datapayload中,我需要传递检索到的字段。但它显示错误未定义

  

云功能

const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.splitting  = functions.firestore
    .document('deyaPayUsers/{authid}/Split/{authid1}/SentInvitations/{autoid}')// Here the path is is triggereing
    .onWrite(event =>{
    var  id = event.params.authid;//here we get the authid of the user who triggeres.
    var dbref = db.collection('deyaPayUsers').doc(id);
    var sendername ;
    var getDoc = dbref.get()
                .then(doc =>{
                if(!doc.exists){
                    console.log("No Such Document");
                    }else{
                    console.log('Document data of the firstname', doc.data().FirstName);
                    sendername = doc.data().FirstName;
                    }
                    console.log("sent"+sendername);
                })
                .catch(err => {
                console.log("error getting document",err);
                });
    console.log(id);
    var id1 = event.params.authid1;
    var  splitid = event.params.autoid;
    console.log("laha"+sendername);
    var document = event.data.data();
    var phoneNumber = [];
    //In loop
    for(var k in document){ // this line says about looping the document to get the phonenumber field in all the invites
    phoneNumber.push(document[k].PhoneNumber);// All the phonenumbers are stored in the phoneNumber array.
    }
    console.log("The json data is " +phoneNumber);
    var ph1 = document.Invite1.PhoneNumber;//It  gets the single user phoneumber in Invite1
    var amount = document.Invite1.Amount;//It gets the amount of the single user in invite1 in integer
    var a = amount.toString();// It is used to convert the Integer amount into String
    console.log(a);
    console.log(document);
    console.log(ph1);
  var deyaPay = db.collection("deyaPayUsers");// This path is user profile path to query with phonenumber
  for(var k in document){ // here It is the loop in a document to get the phonenumber
     var p = document[k].PhoneNumber;// here we get the phonenumber for every loop in invite and stored in p variable
     var am = document[k].Amount;// we get the amount of that invite
     var ams = am.toString();// converting integer amount into string
     console.log("AMount of the user"+ams);

  let phQuery = deyaPay.where('PhoneNumber','==',p)// This line says that checking the user proile PhoneNumber field and the document phonenumber which is stored in p variable.
.get()
   .then(snapshot => {
        snapshot.forEach(doc=>{ // It loops all the documnets whether the PhoneNumbers are matching with user profiles phonenumber
            console.log(doc.id, " => ", doc.data());// If matches it prints the doc id and the user data
                       var userData = doc.data();//Here we get the doc data of that matched phonenumber
                       var userId = doc.id;// here it we get the id of the Matched profile
                       var FirstName = userData.FirstName;
                         console.log(FirstName);
                         var LastName = userData.LastName;
                          console.log(FirstName);
                       var FullName = FirstName + LastName;
                        console.log(FullName);
                       var Token = userData.FCMToken; // we need to take that fcm token to send the notification
                       console.log(userId);
                       console.log("FCM Token for that phoneNumber" + Token);
                       console.log(userData.PhoneNumber);
                       console.log(ph1 + "Exist In DB");
                       var msg = FirstName +  " "+ "requested you to pay $" +ams;
                       console.log("total notification is" +msg);


   let payload = {       //This is for sending notification message
        notification: {
            title: "Message",
            body:  msg,
            sound: "default",

        },
        'data':{// these is the data it calls in the messagereceived method
                'Name':sendername,
                'Amount':ams
        }
    };
console.log(payload);
   return admin.messaging().sendToDevice(Token, payload).then((response)=> { // This method is used for returning the notification to a specific device
    console.log(Token);
      console.info("Successfully sent notification")
    }).catch(function(error) {
        console.warn("Error sending notification " , error)
        });
                });


 }) .catch(err => {
                    console.log('Error getting documents', err);
                                   });
                                   }

 });

1 个答案:

答案 0 :(得分:0)

试试这个,问题是每当你在node.js中执行任何异步操作时,它都不会等待它完成下一行的执行。

const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.splitting = functions.firestore
    .document('deyaPayUsers/{authid}/Split/{authid1}/SentInvitations/{autoid}') // Here the path is is triggereing
    .onWrite(async (event) => {
        try {
            const responses = [];
            var id = event.params.authid; //here we get the authid of the user who triggeres.
            var dbref = db.collection('deyaPayUsers').doc(id);
            var sendername;
            var doc = await dbref.get();

            if (!doc.exists) {
                console.log("No Such Document");
            } else {
                console.log('Document data of the firstname', doc.data().FirstName);
                sendername = doc.data().FirstName;
            }

            console.log(id);
            var id1 = event.params.authid1;
            var splitid = event.params.autoid;
            console.log("laha" + sendername);
            var document = event.data.data();
            var phoneNumber = [];
            //In loop
            for (var k in document) { // this line says about looping the document to get the phonenumber field in all the invites
                phoneNumber.push(document[k].PhoneNumber); // All the phonenumbers are stored in the phoneNumber array.
            }
            console.log("The json data is " + phoneNumber);
            var ph1 = document.Invite1.PhoneNumber; //It  gets the single user phoneumber in Invite1
            var amount = document.Invite1.Amount; //It gets the amount of the single user in invite1 in integer
            var a = amount.toString(); // It is used to convert the Integer amount into String
            console.log(a);
            console.log(document);
            console.log(ph1);
            var deyaPay = db.collection("deyaPayUsers"); // This path is user profile path to query with phonenumber
            for (var k in document) { // here It is the loop in a document to get the phonenumber
                var p = document[k].PhoneNumber; // here we get the phonenumber for every loop in invite and stored in p variable
                var am = document[k].Amount; // we get the amount of that invite
                var ams = am.toString(); // converting integer amount into string
                console.log("AMount of the user" + ams);
                let snapshot = await deyaPay.where('PhoneNumber', '==', p) // This line says that checking the user proile PhoneNumber field and the document phonenumber which is stored in p variable.
                    .get();
                snapshot.forEach(doc => { // It loops all the documnets whether the PhoneNumbers are matching with user profiles phonenumber
                    console.log(doc.id, " => ", doc.data()); // If matches it prints the doc id and the user data
                    var userData = doc.data(); //Here we get the doc data of that matched phonenumber
                    var userId = doc.id; // here it we get the id of the Matched profile
                    var FirstName = userData.FirstName;
                    console.log(FirstName);
                    var LastName = userData.LastName;
                    console.log(FirstName);
                    var FullName = FirstName + LastName;
                    console.log(FullName);
                    var Token = userData.FCMToken; // we need to take that fcm token to send the notification
                    console.log(userId);
                    console.log("FCM Token for that phoneNumber" + Token);
                    console.log(userData.PhoneNumber);
                    console.log(ph1 + "Exist In DB");
                    var msg = FirstName + " " + "requested you to pay $" + ams;
                    console.log("total notification is" + msg);
                    let payload = { //This is for sending notification message
                        notification: {
                            title: "Message",
                            body: msg,
                            sound: "default",

                        },
                        'data': { // these is the data it calls in the messagereceived method
                            'Name': sendername,
                            'Amount': ams
                        }
                    };
                    console.log(payload);
                    const response = await admin.messaging().sendToDevice(Token, payload)
                    console.info("Successfully sent notification")
                    responses.push(response);
                });
            };
            return responses; //here
        } catch (error) {
            console.info("error", error)
        }
    });