0

I am working on a mobile chat application to learn how to use cloud services and have been having some difficulty updating my array of maps without overwriting the array. I have tried multiple different ways but I can only either get it so it overwrites the whole array, or does nothing. I was trying to follow the documentation from firebase for NodeJS to append to the array but cannot get it to work. Any tips on what I am doing wrong? (in my code: db = firebase.firestore();)

sendMessage = async e => {
        e.preventDefault();
        let date = new Date();

        const res2 = await db.collection('indivualChats').doc(this.state.chatID).update({
            messages: db.FieldValue.arrayUnion({
                mid: res.id,
                msg: this.state.message,
                timeSent: date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear(),
                uid: auth.currentUser.uid})
            });

        this.setState({
            message: '',
        })
};

cloud data layout

1 Answers1

0

From Doug's answer you can't direct update of a specific index of array. The alternative way is to read the entire document, modify the data in memory and update the field back into the document or based on the document you can use arrayUnion() and arrayRemove() to add and remove elements.

My example:

Data structure:

enter image description here

Codes in nodejs:

async function transaction(db) {
    const ref = db.collection('users').doc('john');
    try {
    await db.runTransaction(async (t) => {
        const doc = await t.get(ref)
        const newmessage = 'hello world!';
        t.update(ref, {
            "message": admin.firestore.FieldValue.arrayUnion({
                text: newmessage
            })
        });
        t.update(ref, {
            'message': admin.firestore.FieldValue.arrayRemove({
                    text:doc.data().message[0].text
            })
        })
    });

        console.log('Transaction success!');
    } catch (e) {
        console.log('Transaction failure:', e);
    }
}
transaction(db);
JM Gelilio
  • 3,482
  • 1
  • 11
  • 23