簡體   English   中英

如何將對象推入數組 firebase

[英]How to push object into array firebase

我正在嘗試將一個對象推送到一個數組中,該數組在 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中的存儲方式在此處輸入圖片說明

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM