【问题标题】:How to push object into array firebase如何将对象推入阵列 Firebase
【发布时间】:2021-09-12 03:21:44
【问题描述】:

我正在尝试将一个对象推送到一个数组中,该数组在 firebase 中存储给用户。 我有这个。它从点击开始

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

控制台没有错误,但它没有向用户数组添加任何内容。

这是点击功能

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

我不知道为什么它没有添加到数组中。这是它在firestore中的存储方式

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    .push() 不适合这个任务;您必须使用 firebase.firestore.FieldValue.arrayUnionfirebase.firestore.FieldValue.arrayRemove 在 Firestore 中执行数组操作。
    请参阅 https://firebase.google.com/docs/firestore/manage-data/add-data#web-v8_11

    类似的东西(假设支持数据类型object):

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

    还有 admin.firestore.FieldValue 对应的,但这些是针对 NodeJS 的。

    【讨论】:

      【解决方案2】:

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

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

      要从数组中删除项目,您必须将确切的值传回arrayRemove 函数。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-08
        • 1970-01-01
        • 1970-01-01
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多