1

I am trying to push an object into an array that is stored to the user in firebase. I have this. It starts on click

  function savetodb() {
    auth.onAuthStateChanged(user => {
    if(user) {
      db.collection('users').doc(user.uid).get().then(doc => {
        const saveditems1 = doc.data().saveditems
 saveditems1.push({
          Name:'Test',
          Price:'Test',
          Link:'https://www.test.com'
        })
        
    });
    }
    else {
return alert('no')
    }
})

There is no errors in the console, but it doesn't add anything to the user's array.

Here is the on click function

     <button id="savedb" onclick='savetodb()'>Save For Later</button>

I don't know why It isn't adding to the array. Here is how it is stored in firestore enter image description here

2 Answers 2

1

Firestore arrays don't support index'd arrays that you can push into, behind the scenes they use ordered lists and you must invoke an arrayUnion Firestore function. It is important to note that the document does not need to exist if you use set:merge methods as arrayUnion will generate the array if it does not exist.

const data = {
        Name: 'Test',
        Price: 'Test',
        Link: 'https://www.test.com'
    }
doc.set({
    saveditems: firebase.firestore.FieldValue.arrayUnion(data)
},
{merge:true});

To remove items from an array, you must pass the exact value back to an arrayRemove function.

const data = {
        Name: 'Test',
        Price: 'Test',
        Link: 'https://www.test.com'
    }
doc.update({
    saveditems: firebase.firestore.FieldValue.arrayRemove(data)
});
Sign up to request clarification or add additional context in comments.

Comments

0

.push() isn't suitable for the task; you'd have to use firebase.firestore.FieldValue.arrayUnion and firebase.firestore.FieldValue.arrayRemove to perform array-manipulation in Firestore.
See https://firebase.google.com/docs/firestore/manage-data/add-data#web-v8_11.

Something alike (assuming that data-type object is being supported):

doc.update({
    saveditems: firebase.firestore.FieldValue.arrayUnion({
        Name: 'Test',
        Price: 'Test',
        Link: 'https://www.test.com'
    })
});

There's also admin.firestore.FieldValue counterparts, but these are for NodeJS.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.