Firebase firestore云功能显示错误:无效使用“undefined”类型作为Firestore参数

问题描述 投票:19回答:2

我有一个项目将货币详细信息添加到firestore数据库中,我的项目正在使用ionic 3

每当我向集合添加新文档时,触发函数onCreate()将执行并更新名为“updated”的文档。

但触发功能始终显示错误。

Error: Invalid use of type "undefined" as a Firestore argument.
    at Object.exports.customObjectError.val [as customObjectError] (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/validate.js:164:14)
    at Function.encodeValue (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:808:20)
    at Function.encodeFields (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:678:36)
    at Function.fromObject (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:218:55)
    at WriteBatch.set (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/write-batch.js:291:39)
    at DocumentReference.set (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/reference.js:419:8)
    at Object.<anonymous> (/user_code/lib/index.js:28:10)
    at next (native)
    at /user_code/lib/index.js:7:71
    at __awaiter (/user_code/lib/index.js:3:12)

有人请帮忙..

我花了很多时间。

这是代码:

import * as functions from 'firebase-functions';

const admin = require('firebase-admin');
admin.initializeApp();

exports.createCurrency = functions.firestore
.document('Exchange/{ExchangeId}')
.onCreate( async (snap, context) => {

const id: string = snap.data().id;
const branchName: string = snap.data().branchName;
const currencyName: string = snap.data().currencyName;
const buyingRate : string = snap.data().buyingRate;
const sellingRate : string = snap.data().sellingRate;


 const newUser= admin.
 firestore()
 .doc(`Exchange/updated`)
 .set({
   id : id,
   branchName : branchName,
   currencyName : currencyName,
   sellingRate : sellingRate,
   buyingRate :buyingRate
  });

 return newUser;


 });
javascript firebase google-cloud-firestore google-cloud-functions
2个回答
38
投票

错误消息是这样的:

Invalid use of type "undefined" as a Firestore argument.

您可以在堆栈跟踪中看到,当您使用DocumentReference上的对象调用set()时,会发生这种情况。事实证明,您在对象中传递的值之一是未定义的。检查您传递的每个值,并确保它们都具有实际值:

 .set({
   id : id,
   branchName : branchName,
   currencyName : currencyName,
   sellingRate : sellingRate,
   buyingRate :buyingRate
  });

从错误信息中分辨出它是不可能的,所以你必须将它们全部打印出去做一些检查它们的每一个。


1
投票

当你.set一个对象,但对象中的一个字段未定义时,你将收到此错误。

问题是,当您使用console.log显示对象时,它不会显示未定义的变量,因此很难跟踪。

使用以下代替console.log来查找导致问题的元素。

const util = require('util');
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

这将为您提供如下输出:

{ origin: 'AMS',
  destination: undefined,
  duration: 94,
  carrier: 'KL',
  flight_number: '2977',
  departure: '2019-06-11T15:34:00',
  arrival: '2019-06-11T17:08:00',
  type: 'flight' }
© www.soinside.com 2019 - 2024. All rights reserved.