如何更新阵列字段?

时间:2018-01-14 15:12:11

标签: javascript firebase google-cloud-functions google-cloud-firestore firebase-admin

我正在使用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);
  });  

  });

2 个答案:

答案 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)

我已经进一步研究了这件事,我会按照弗兰克在他的帖子中给你的建议;在集合中而不是在数组中分配数据,因为它们对Firebase 1具有更大的多功能性。根据Firebase网站上列出的示例进行研究,寻找与聊天相关的任何内容,我找到了Firechat使用的消息的数据结构和代码,因为它们可能对您有用。

在源代码中,他们使用带有以下拓扑2的message-id -userId对的集合: Topology of the Example

在存储库中执行保存的确切方式是3Append sentence

它将消息附加到Room-id集合中。您可以使用userID - messageID对代替此结构,因为它可能更适合您。