获取文档ReferenceError时出错:未定义from_data

时间:2018-12-07 12:49:01

标签: node.js google-cloud-firestore google-cloud-functions

嗨,我被卡在获取文档时出错的那部分。我想获取用户名的字段。

这是我从控制台日志中得到的结果:来自用户ID:PGIfPp8wmnR1PB1XeiBfUgSnGO62来自用户:[object Promise]到用户ID [object Promise]。

我在做什么错了?

index.js

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

const db = admin.firestore();

exports.sendNotification = functions.firestore.document('users/{userID}/notifications/{notificationID}')
    .onWrite((change, context) => {

        const user_id = context.params.userID;
        const notification_id = context.params.notificationID;

        console.log('We have notification from: ' + user_id + ' The notification id is: ' + notification_id);

        return db.collection('users').doc(user_id)
            .collection('notifications').doc(notification_id).get().then(queryResult => {
                if (!queryResult.exists) {
                    console.log('No documents');
                }else{
                    console.log("Document data: " ,queryResult.data());
                    const from_user_id = queryResult.data().from;
                    const from_data = admin.firestore().collection('users').doc(from_user_id).get();
                    const to_data = admin.firestore().collection('users').doc(user_id).get();

                    console.log("From user id: " + from_user_id + "From user: " + from_data + " To user id " + to_data);

                }
                return Promise.all([from_data, to_data]).then(result => {

                    const from_name = result[0].data().name;
                    const to_name = result[1].data().name;

                    return console.log("FROM: " + from_name + " TO: " + to_name);
                });
            }).catch(err =>{
                console.error('Error getting document', err);
            })
    });

我遇到错误

Error getting document ReferenceError: from_data is not defined
    at db.collection.doc.collection.doc.get.then.queryResult (/user_code/index.js:31:37)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

1 个答案:

答案 0 :(得分:0)

在这两行中:

const from_data = admin.firestore().collection('users').doc(from_user_id).get();
const to_data = admin.firestore().collection('users').doc(user_id).get();

您正在为将用文档数据解决的Promise赋值。您还没有实际的文档数据。您需要使用get()返回的promise来查找实际数据,就像您在函数中的早期操作一样。