Firestore:无法序列化“ ArrayUnionTransform”类型的对象

时间:2018-12-25 20:14:57

标签: javascript firebase google-cloud-firestore

我正在尝试使用Firestore文档示例更新数组中的元素:

https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

var admin = require('firebase-admin');

var washingtonRef = firestore.collection('cities').doc('DC');

var arrUnion = washingtonRef.update({
  regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});

但是,当我这样做时,会出现以下错误:

Error: Update() requires either a single JavaScript object or an 
alternating list of field/value pairs that can be followed by an 
optional precondition. Argument "dataOrField" is not a valid Document. 
Couldn't serialize object of type "ArrayUnionTransform" (found in field 
regions). Firestore doesn't support JavaScript objects with custom 
prototypes (i.e. objects that were created via the "new" operator).

1 个答案:

答案 0 :(得分:0)

确保您使用的是正确的SDK。

之所以不起作用,是因为我对firestore.collection('cities').doc('DC');的引用实际上来自这里:

const Firestore = require('@google-cloud/firestore'); // this is the wrong SDK.

const firestore = new Firestore({
  projectId: 'my-project'
  keyFilename: fbKeyFile
});

如在README.md上所述,这是错误的:

  

使用Google服务器SDK的应用程序不得在最终用户环境中使用,例如在电话或公共托管的网站上。如果您正在开发代表最终用户访问Cloud Firestore的Web或Node.js应用程序,请使用firebase Client SDK。

因此,为了使其正常工作,我简单地切换了以下内容:

firestore.collection('cities').doc('DC');
// to
FirebaseAdmin.firestore().collection('cities').doc('DC');