简体   繁体   中英

React Native Expo Firebase v9.9.x Firestore add value to array

My database looks like this:

  • collection id: "my-collection"
  • each user gets a document which name is user id
  • each document consist out of one array "data" which holds maps:
data: [{"prop1" : "1", "prop2" : "2"}, {"prop1" : "4", "prop2" : "1"}]

I can create the document with

import { getFirestore } from 'firebase/firestore';
import { getAuth } from "firebase/auth";

// Class component that wraps my code...
const firestoreDb = getFirestore();
const user = getAuth().currentUser;
const document = doc(firestoreDb, "my-collection", user.uid);

setDoc(document, {
  data: []
}).then(() => console.log("Created user document.").catch(err => console.log(err));

How can I add elements to the data array? I know there exists a function updateDoc , but I don't know how to use it and cannot find any documentation.

Please note that in this version the firestore.collection() method does not exist.

Thanks to the answers the following is a solution:

import { getAuth } from "firebase/auth";
import { arrayUnion, updateDoc, getFirestore } from 'firebase/firestore';

const firestoreDb = getFirestore();
const user = getAuth().currentUser;
const document = doc(firestoreDb, "my-collection", user.uid);
updateDoc(document, { data: arrayUnion({"prop1": "5", "prop2", "6"}) })
    .then(() => {
        console.log("Updated document");
    })
    .catch(err => console.log(err));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM