我正在使用Firebase Firestore并希望使用最新聊天线程的id更新userprofile下的数组字段。我猜我必须从该用户下的聊天节点拉出整个数组(如果存在),然后我需要附加新的id(如果它不存在)并更新数组..当数组中只有1个值然后它失败后,它会起作用,并出现以下错误:
事务失败:{错误:无法转换数组值中的数组值。 at /user_code/node_modules/firebase-admin/node_modules/grpc/src/node/src/client.js:554:15代码:3,元数据:元数据{_internal_repr:{}}}
这是我的firebase云功能,谁能告诉我哪里出错?
exports.updateMessages = functions.firestore.document('messages/{messageId}/conversation/{msgkey}').onCreate( (event) => {
/// console.log('function started');
const messagePayload = event.data.data();
const userA = messagePayload.userA;
const userB = messagePayload.userB;
// console.log("userA " + userA);
// console.log("userB " + userB);
// console.log("messagePayload " + JSON.stringify(messagePayload, null, 2) );
const sfDocRef = admin.firestore().doc(`users/${userB}`);
return admin.firestore().runTransaction( (transaction) => {
return transaction.get(sfDocRef).then( (sfDoc) => {
const array = [];
array.push(...[event.params.messageId, sfDoc.get('chats') ]);
transaction.update(sfDocRef, { chats: array } );
});
}).then( () => {
console.log("Transaction successfully committed!");
}).catch( (error) => {
console.log("Transaction failed: ", error);
});
});
答案 0 :(得分:3)
您可以在代码中嵌入数组:
const array = [];
array.push(...[event.params.messageId, sfDoc.get('chats') ]);
这导致array
有两个值,第一个是新的messageId
,第二个值包含所有先前值的数组,例如
[ "new message id", ["previous id", "older id"] ]
这种类型的嵌套数组是Firestore(显然)不允许存储的内容。
解决方案很简单:
const array = [event.params.messageId, ...sfDoc.get('chats')];
您必须首先加载数组然后向其添加单个元素,这是Firebasers建议不在数组中存储数据的原因之一。您的当前数据看起来更像是一组,如the Firestore documenation所示:
{
"new message id": true,
"previous id": true,
"older id": true
}
这样添加聊天ID非常简单:
sfDocRef.update({ "chats."+event.params.messageId, true })
答案 1 :(得分:0)