firebase Firestore将值添加到数组字段

roejwanj  于 2023-08-07  发布在  其他
关注(0)|答案(4)|浏览(105)

我试图使用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( () => {

        });

  });

字符串
这是我的数据库的样子


的数据
任何提示非常感谢,我是新来firestore。

a6b3iqyw

a6b3iqyw1#

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

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')
});

字符串

kmynzznz

kmynzznz2#

Firestore当前不允许您更新数组的各个字段。但是,您可以将数组的全部内容替换为如下:

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

字符串
请注意,这可能会覆盖来自其他客户端的某些写入。您可以在执行更新之前使用事务处理锁定文档。

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

yxyvkwin

yxyvkwin3#

这是2021年,在Firebase Firestore的多次更新之后,在数组中添加数据而不删除另一个数据的新方法是

var washingtonRef = db.collection("cities").doc("DC");

      // Atomically add a new region to the "regions" array field.
       washingtonRef.update({
     regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
     });

      // Atomically remove a region from the "regions" array field.
    washingtonRef.update({
        regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
      });

字符串

41ik7eoe

41ik7eoe4#

firebase 9.x:

import { getFirestore, FieldValue } from 'firebase-admin/firestore';
import { initializeApp } from 'firebase-admin/app';
import admin from "firebase-admin";

const firebaseAdminApp = initializeApp ({
   credential: admin.credential.cert(serviceAccountCreds) 
});

const db = getFirestore(firebaseAdminApp);

let collectionName = 'cities';
let docID = 'DC'

let docRef = await db.collection(collectionName).doc(docID);
await docRef.update({regions: FieldValue.arrayUnion('Northern Virginia')});

字符串

相关问题