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



嗨,我在获取文档时遇到了错误。我想获取用户名的字段。

这是我从控制台日志中得到的结果:from user-id:PGIfPp8wmnR1PB1XeiBfUgSnGO62From user:[object Promise]To user-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)

在这两行中:

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

您正在将值分配给将通过文档数据解决的承诺。您还没有得到实际的文档数据。您需要使用get()返回的promise来查找实际数据,就像前面在函数中所做的那样。

相关内容

  • 没有找到相关文章

最新更新