【发布时间】:2018-06-23 08:58:54
【问题描述】:
我正在使用 Firebase Firestore,并希望使用最新聊天线程的 id 更新用户配置文件下的数组字段。我猜我必须从该用户下的聊天节点中提取整个数组(如果存在),然后我需要附加新的 id(如果它不存在)并更新数组。当数组中只有 1 个值时它可以工作,然后它会失败并出现以下错误:
事务失败:{ 错误:无法将数组值转换为数组值。 在 /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);
});
});
【问题讨论】:
-
这是 Firebases 建议不要将数据存储在数组中的原因之一。您当前的数据看起来像一组更好,如下所示:firebase.google.com/docs/firestore/solutions/arrays。这样添加聊天 ID 就像
sfDocRef.update({ "chats."+event.params.messageId, true })一样简单。
标签: javascript firebase google-cloud-functions google-cloud-firestore firebase-admin