简体   繁体   English

如何将对象推入数组 firebase

[英]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.我正在尝试将一个对象推送到一个数组中,该数组在 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中的存储方式在此处输入图片说明

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. Firestore 数组不支持您可以推入的索引数组,它们在幕后使用有序列表,您必须调用arrayUnion Firestore 函数。 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.重要的是要注意,如果使用set:merge方法,则文档不需要存在,因为如果数组不存在, arrayUnion将生成数组。

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.要从数组中删除项目,您必须将确切的值传递回arrayRemove函数。

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; .push()不适合该任务; you'd have to use firebase.firestore.FieldValue.arrayUnion and firebase.firestore.FieldValue.arrayRemove to perform array-manipulation in Firestore.您必须使用firebase.firestore.FieldValue.arrayUnionfirebase.firestore.FieldValue.arrayRemove在 Firestore 中执行数组操作。
See https://firebase.google.com/docs/firestore/manage-data/add-data#web-v8_11 .请参阅https://firebase.google.com/docs/firestore/manage-data/add-data#web-v8_11

Something alike (assuming that data-type object is being supported):类似的东西(假设支持数据类型object ):

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.还有admin.firestore.FieldValue对应物,但这些是用于 NodeJS 的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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