How to show data from firebase database in nodeJS

I want to send user name in the mail but instead of name , a URL of that name is send every time. Here is my code

exports.onUserCreated = functions.database.ref('/user/{pushId}/email')
    .onCreate((snapshot, context ) => {
      // Do something when a new user is created
      var email = snapshot.val();

      var name = snapshot.ref.parent.child('name');

      return sendWelcomeEmaill(email, name);
    });


function sendWelcomeEmaill(email, name){
const mailOptions = {

    from :  `${APP_NAME} <noreply@firebase.com>`,
    to: email,
  };

mailOptions.subject = `Welcome to ${APP_NAME}!`;
mailOptions.text = `Hey ${name || ''}! Welcome to ${APP_NAME}. \n\n We hope you will enjoy our service.`;
return mailTransport.sendMail(mailOptions).then(() => {
  return console.log('New welcome email sent to:', email);
});
}

Here in this line the problem occurs

var name = snapshot.ref.parent.child('name');

The output should be in text rather than url of name in user

The database be like

user
   -h(random pushID)
     |---email: "yostar18888@gmail.com"
     |---name : "manik"

1 answer

  • answered 2019-01-11 10:28 Renaud Tarnec

    By doing

    var name = snapshot.ref.parent.child('name');
    

    you actually assign a Reference to the variable name, since the child() method returns a Reference.

    So you need to query the value at this reference, by doing

    exports.onUserCreated = functions.database.ref('/user/{pushId}/email')
        .onCreate((snapshot, context ) => {
          // Do something when a new user is created
          var email = snapshot.val();
    
          var nameRef = snapshot.ref.parent.child('name');  //Note that variable name was changed to nameRef, to be more meaningful
    
          return nameRef.once('value')
          .then(function(dataSnapshot) {
             return sendWelcomeEmaill(email, dataSnapshot.val());
          });
    
     });
    

    In case you set the name and the email of a user at the same time, it may be easier to trigger the Cloud Function at the level of the user node instead of the level of the email one, like:

    exports.onUserCreated = functions.database.ref('/user/{pushId}')
        .onCreate((snapshot, context ) => {
          // Do something when a new user is created
          var email = snapshot.val().email;
          var name = snapshot.val().name;
          ......