【问题标题】:Snapshot.val() returns the last attribute of the objectSnapshot.val() 返回对象的最后一个属性
【发布时间】:2021-07-15 03:03:20
【问题描述】:

我正在使用 firebase 云功能来检测我的实时数据库 ref ("/Project Request/{pushId}") 上的新创建,我需要从该创建中获取数据并将其添加到 Fire Store 以发送电子邮件。但是获取 snapshot.val();出于某种奇怪的原因,仅返回带有最后一个属性的对象。

exports.sendMail = functions.database.ref('/Project Request/{pushId}').onCreate( (event, context) => {

  const requestId = context.params.pushId;

  const data = event.val();
  console.log("Data:  " + data['etProjectTitle']);
  console.log("Data:  " + data.etProjectTitle);

  admin.firestore().collection('project request mails').add({
    to: 'mymail@gmail.com',
    message: {
      subject: 'Project Request!',
      html: "Project Title:   " + data['etProjectTitle'] + 
            "<br>" + 
            "Project Description:   " + data.project_description +
            "<br>" + 
            "Project Technology:   " + data.project_technology +
            "<br>" + 
            "User Email:   " + data.user_email +
            "<br>" + 
            "User Name:   " + data.user_name, 
    },
  });
});

console.log 语句打印 undefined 并且这也在邮件中发送。 html 属性中提到的所有属性(即 data.user_email)确实存在于数据库中,但由于某种原因,我只得到 { user_name:“我的用户名”}。 数据从 android 应用程序添加到 ref("Project Request")。

project_request =FirebaseDatabase.getInstance().getReference().child("Project Request");

DatabaseReference newPost = project_request.push();
newPost.child("user_name").setValue(mAuth.getCurrentUser().getDisplayName());                   newPost.child("user_email").setValue(mAuth.getCurrentUser().getEmail());
newPost.child("Phone No").setValue(mPhone);
newPost.child("etProjectTitle").setValue(mTitle);
newPost.child("project_description").setValue(mDesc);
newPost.child("project_technology").setValue(mTech);
newPost.child("project_proposal").setValue("N/A");

db 看起来像这样。

【问题讨论】:

  • 能否展示在/Project Request下写入新数据的代码?如果您可以使用硬编码数据重现它,或者非常明确地向我们展示添加了什么 JSON,这将特别有用。
  • 编辑了上面的问题。请看一下。 @FrankvanPuffelen

标签: javascript firebase firebase-realtime-database google-cloud-firestore google-cloud-functions


【解决方案1】:

问题是每次调用setValue 都是对数据库的单独写入。 path 下的第一次写入会创建该路径,这会触发您的 onCreate Cloud 函数。因此,当 Cloud Function 代码运行时,只有 user_name 可用。

解决方案是执行单个写入操作,结合您要设置的所有属性:

DatabaseReference newPost = project_request.push();
Map<String,Object> values = new HashMap<>();
values.put("user_name", mAuth.getCurrentUser().getDisplayName());                   values.put("user_email", mAuth.getCurrentUser().getEmail());
values.put("Phone No", mPhone);
values.put("etProjectTitle", mTitle);
values.put("project_description", mDesc);
values.put("project_technology", mTech);
values.put("project_proposal", "N/A");
newPost.setValue(values);

现在,由于只需一次调用 setValue,所有数据都一次性写入,您的 Cloud Function 可以读取所有属性。

【讨论】:

  • 有道理...!我会尽快更新你.. 不过谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2014-03-15
  • 1970-01-01
  • 2020-04-06
相关资源
最近更新 更多