如何在nodeJS中显示来自Firebase数据库的数据

时间:2019-01-11 05:28:42

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

我想在邮件中发送用户名,但是每次都会发送该名称的URL而不是name。这是我的代码

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);
});
}

此行出现问题

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

输出应为文本,而不是用户名称的url

数据库就像

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

1 个答案:

答案 0 :(得分:1)

这样做

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

实际上,您将Reference分配给了变量name,因为child()方法返回了一个引用。

因此您需要通过执行以下操作来查询此引用处的值

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());
      });

 });

如果您同时设置用户的名称和电子邮件 ,则可能更容易在user节点级别触发Cloud Function,而不是email的级别,例如:

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;
      ......