简体   繁体   中英

How to push object into array firebase

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在此处输入图片说明

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

.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.

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