node.js Firestore 将值添加到数组字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48231957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:38:54  来源:igfitidea点击:

Firestore Add value to array field

node.jsfirebasegoogle-cloud-functionsgoogle-cloud-firestorefirebase-admin

提问by Kravitz

Im trying to use Firebase cloud functions to add the id of a chatroom to the users document in an array field. I cant seem to figure out the way to write to an array field type. here is my cloud function

我正在尝试使用 Firebase 云函数将聊天室的 id 添加到数组字段中的用户文档中。我似乎无法弄清楚写入数组字段类型的方法。这是我的云功能

  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;   

        return admin.firestore().doc(`users/${userA}/chats`).add({ event.params.messageId }).then( () => {

        });

  });

here is the way my database looks

这是我的数据库的样子

enter image description here

在此处输入图片说明

any tips greatly appreciated, Im new to firestore.

非常感谢任何提示,我是 Firestore 的新手。

回答by Sean Blahovici

From the docs, they added a new operation to append or remove elements from arrays. Read more here: https://firebase.google.com/docs/firestore/manage-data/add-data

从文档中,他们添加了一个新操作来添加或删除数组中的元素。在此处阅读更多信息:https: //firebase.google.com/docs/firestore/manage-data/add-data

Example:

例子:

var admin = require('firebase-admin');
// ...
var washingtonRef = db.collection('cities').doc('DC');

// Atomically add a new region to the "regions" array field.
var arrUnion = washingtonRef.update({
  regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
var arrRm = washingtonRef.update({
  regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});

回答by Sebastian Schmidt

Firestore currently does not allow you to update the individual fields of an array. You can, however, replace the entire contents of an array as such:

Firestore 目前不允许您更新数组的各个字段。但是,您可以像这样替换数组的全部内容:

admin.firestore().doc(`users/${userA}/chats`).update('array', [...]);

Note that this might override some writes from another client. You can use transactions to lock on the document before you perform the update.

请注意,这可能会覆盖来自另一个客户端的某些写入。在执行更新之前,您可以使用事务来锁定文档。

admin.firestore().runTransaction(transaction => {
  return transaction.get(docRef).then(snapshot => {
    const largerArray = snapshot.get('array');
    largerArray.push('newfield');
    transaction.update(docRef, 'array', largerArray);
  });
});