开发者社区 问答 正文

如何使用Firestore更新“对象数组”?

我目前正在尝试使用Firestore,但遇到了非常简单的问题:“更新数组(又称子文档)”。

我的数据库结构非常简单。例如:

proprietary: "John Doe", sharedWith: [ {who: "first@test.com", when:timestamp}, {who: "another@test.com", when:timestamp}, ], 我正在尝试(没有成功)将新记录推入shareWith对象数组。

我试过了:

// With SET firebase.firestore() .collection('proprietary') .doc(docID) .set( { sharedWith: [{ who: "third@test.com", when: new Date() }] }, { merge: true } )

// With UPDATE firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: [{ who: "third@test.com", when: new Date() }] }) 没有效果。这些查询将覆盖我的数组。

答案可能很简单,但我找不到它... 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 20:01:26 763 分享 版权
1 条回答
写回答
取消 提交回答
  • 您可以使用事务(https://firebase.google.com/docs/firestore/manage-data/transactions)获取数组,将其压入数组,然后更新文档:

    const booking = { some: "data" };
    const userRef = this.db.collection("users").doc(userId);
    
    this.db.runTransaction(transaction => {
        // This code may get re-run multiple times if there are conflicts.
        return transaction.get(userRef).then(doc => {
            if (!doc.data().bookings) {
                transaction.set({
                    bookings: [booking]
                });
            } else {
                const bookings = doc.data().bookings;
                bookings.push(booking);
                transaction.update(userRef, { bookings: bookings });
            }
        });
    }).then(function () {
        console.log("Transaction successfully committed!");
    }).catch(function (error) {
        console.log("Transaction failed: ", error);
    });
    
    2020-02-08 20:01:41
    赞同 展开评论
问答分类:
问答地址: