简体   繁体   English

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

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

I'm trying to fetch a single field value from a doc in a collection (stored in Firestore).我正在尝试从集合中的文档(存储在 Firestore 中)中获取单个字段值。 The following function is called (by the triggered function) to perform this query and return the result.调用以下 function(由触发函数)执行此查询并返回结果。

Firestore data structure: Firestore数据结构: Firestore 数据结构

After I fetch the query result into helper_token object - I cannot access the DATA (fields) in it.在我将查询结果提取到helper_token object 之后 - 我无法访问其中的数据(字段)。 I tried many things, including:我尝试了很多东西,包括:

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

Nothing works for me.什么都不适合我。 The log always shows results like these:日志总是显示如下结果:

helper_token = {}
helper_token = undefined

What am I missing?我错过了什么? how can I get the device_token based on user ?如何根据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;
};

For completeness, adding here the full calling function to the above function:为了完整起见,在这里将完整的调用 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);


    });

You need to consider that the get() call is asynchornous and also that you get a list of documents and not a single doc .您需要考虑get()调用是异步的,并且您得到的是文档列表而不是单个doc Can you try it with this code:你能用这段代码试试吗:

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

As the get() call in Firestore is asynchronous you need to use an asynchronous function. You can go through this article to know more about why Firebase APIs are asynchronous.由于 Firestore 中的get()调用是异步的,因此您需要使用异步 function。您可以通过本文go 详细了解为什么 Firebase API 是异步的。 Next when we query with the where clause in Firestore we get a list of documents even if there is only one document in the list.接下来,当我们在 Firestore 中使用where子句查询时,我们会得到一份文档列表,即使列表中只有一个文档。 So we have to run a for loop to get the document inside the list of documents.所以我们必须运行一个 for 循环来获取文档列表中的文档。 Now as you are returning the value from an asynchronous function the return value will be a promise in pending state. So to get the value from the promise we need to use the then() block while calling the function.现在,当您从异步 function 返回值时,返回值将是待处理 state 中的 promise。因此,要从 promise 中获取值,我们需要在调用 function 时使用then()块。

Also I think the parameter helperId you are using in the function definition is not used anywhere in the function. Though it will not make a difference I would suggest you remove it if it is not required in the function.此外,我认为您在 function 定义中使用的参数helperId未在 function 中的任何地方使用。虽然它不会产生影响,但如果 function 中不需要它,我建议您将其删除。

So consider using the following code -所以考虑使用以下代码 -

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.

相关问题 Firestore 在 object 中使用 where 子句 object 检索文档 - Firestore retrieve docs with where clause object in object Firestore 规则 | 仅在提供文档 ID 时才允许获取文档 - Firestore rules | Allow to get docs only if doc ids is provided 如何在 Firestore 中一次获取一组文档 ID 的所有文档,但只获取这些文档中的部分属性,而不是整个文档? - How to get all documents at once for a set of doc IDs, but only part of the properties in those docs, not the entire docs, in Firestore? 遍历 firestore 文档 - 获取 promise - Iterating over firestore docs - getting a promise Firestore 文档上传后无法路由到仪表板 - Unable to route to dashboard after firestore doc upload React中如何获取Firebase 9中的多个Doc对象? 并使用其文档 ID 从 firestore 获取多个文档? - How to get multiple Doc objects in Firebase 9 in React? and get multiple docs from firestore using its doc id? 我无法访问 firestore 数据库中的两个子集合之一。 反应 - I can't access one of two subcollections in firestore data base. React Firestore 数据无法显示在 RecyclerView 上 - Firestore data can't display on RecyclerView Cloud Firestore 的安全规则 - 用户只能访问他们自己的文档 - Security Rules for Cloud Firestore - User access only their own docs 我想在 flutter 中从 firestore 获取此数据后对数据进行洗牌 - I want to shuffle the data after getting this data from firestore in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM