繁体   English   中英

获取文档后无法访问 Firestore 文档数据 object

[英]Can't access Firestore docs data after getting the doc object

我正在尝试从集合中的文档(存储在 Firestore 中)中获取单个字段值。 调用以下 function(由触发函数)执行此查询并返回结果。

Firestore数据结构: Firestore 数据结构

在我将查询结果提取到helper_token object 之后 - 我无法访问其中的数据(字段)。 我尝试了很多东西,包括:

helper_token[0].device_token;
helper_token.data().device_token;
JSON.stringify(helper_token);

什么都不适合我。 日志总是显示如下结果:

helper_token = {}
helper_token = undefined

我错过了什么? 如何根据user获取device_token

const admin = require('firebase-admin'); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

function getHelperToken(helperId) {
    //Get token from Firestore
    const tokensRef = db.collection('tokens');
    const helper_token = tokensRef.where('user', '==', 'TM1EOV4lYlgEIly0cnGHVmCnybT2').get();
    if (helper_token.empty) {
        functions.logger.log('helper_token EMPTY');
    }
    functions.logger.log('helper_token=' + JSON.stringify(helper_token));

    return helper_token.device_token;
};

为了完整起见,在这里将完整的调用 function 添加到上面的 function 中:

//DB triggered function - upon writing a child in the HElpersInvitations reference
exports.sendHelperInvitation = functions.database.ref('/HelpersInvitations/{helper_invitation_id}')
    .onCreate((snapshot, context) => {

        const helperId = snapshot.val().helperId;
        const title = snapshot.val().title;
        const body = snapshot.val().body;
        
        //Get the helper token by Id
        functions.logger.log('HelperID=' + helperId);
        functions.logger.log('getHelperToken=' + getHelperToken(helperId));
        const helper_token2 = getHelperToken(helperId);
        //Notification payload
        const payload = {
            notification: {
                title: title,
                body: body,
                icon: 'default',
                click_action: 'com.skillblaster.app.helperinvitationnotification' 
            }
        }
        
        //    //Send the notification
            functions.logger.log('helper_token [BEFORE sendToDevice]=' + helper_token2);
            return admin.messaging().sendToDevice(helper_token2, payload);


    });

您需要考虑get()调用是异步的,并且您得到的是文档列表而不是单个doc 你能用这段代码试试吗:

const admin = require("firebase-admin"); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

async function getHelperToken(helperId) {
  //Get token from Firestore
  const tokensRef = db.collection("tokens");
  const helperTokens = await tokensRef
    .where("user", "==", "TM1EOV4lYlgEIly0cnGHVmCnybT2")
    .get();
  let helper_token = "";

  helperTokens.forEach((token) => {
    helper_token = token.data();
  });

  functions.logger.log("helper_token=" + JSON.stringify(helper_token));

  return helper_token.device_token;
}

由于 Firestore 中的get()调用是异步的,因此您需要使用异步 function。您可以通过本文go 详细了解为什么 Firebase API 是异步的。 接下来,当我们在 Firestore 中使用where子句查询时,我们会得到一份文档列表,即使列表中只有一个文档。 所以我们必须运行一个 for 循环来获取文档列表中的文档。 现在,当您从异步 function 返回值时,返回值将是待处理 state 中的 promise。因此,要从 promise 中获取值,我们需要在调用 function 时使用then()块。

此外,我认为您在 function 定义中使用的参数helperId未在 function 中的任何地方使用。虽然它不会产生影响,但如果 function 中不需要它,我建议您将其删除。

所以考虑使用以下代码 -

const admin = require(‘firebase-admin’);
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
 
async function getHelperToken() {
   //Get token from Firestore
   const tokensRef = db.collection(‘tokens’);
   const helper_token = await tokensRef.where(‘user’, ‘==’, ‘TM1EOV4lYlgEIly0cnGHVmCnybT2’).get();
 
   let helper_token_needed;
   helper_token.forEach((token) => {
     helper_token_needed = token.data();
   });
    console.log(helper_token_needed.device_token);
   return helper_token_needed.device_token;
 }
 
//when calling to the function use then() block to get the value as a promise is returned from asynchronous function
getHelperToken().then((value)=>{console.log(value)});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM