【问题标题】:How to update an array within a map using Firestore functions?如何使用 Firestore 函数更新地图中的数组?
【发布时间】:2020-11-22 06:19:33
【问题描述】:

我想使用 Firestore 函数更新地图中的一个数组。我的数据结构如下所示:

在这种情况下,我想更新 {uid} 映射中的 shareRecordsWith 数组。

我一直在尝试使用以下 Firestore 功能,但它不起作用。

const recordsDict = {"uid": aboutUID, "accessType": accessType}
profilesRef.doc(uid).set({
    [uid]: {
        {'shareRecordsWith': admin.firestore.FieldValue.arrayUnion(recordsDict)},
        {merge: true}
    }
});

有没有办法通过 Firestore 函数更新地图中的数组?

编辑:根据建议,我将功能更改为

profilesRef.doc(uid).set({
    [`${uid}.shareRecordsWith`]: admin.firestore.FieldValue.arrayUnion(recordsDict)
}, { merge: true })

不幸的是,它在文档中添加 ${uid}.shareRecordsWith 作为新字段,而不是添加到 {uid} 映射中的 shareRecordsWith 数组中。

这就是它的样子:

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您需要将嵌套字段的整个路径作为单个属性调用。您可以通过将FieldPath 对象与update() 一起传递来做到这一点,但看起来set() 不支持这一点。

    profilesRef.doc(uid).update(
        new admin.firestore.FieldPath(uid, "shareRecordsWith"),
        admin.firestore.FieldValue.arrayUnion(recordsDict)
    })
    

    【讨论】:

    • 不幸的是,它将${uid}.shareRecordsWith 添加为文档中的新字段,而不是添加到 {uid} 映射中的 shareRecordsWith 数组中。我在原始帖子中编辑并附上了屏幕截图。
    • 看起来您必须将 update() 与 FieldPath 一起使用。
    • 在我取出右括号后解决了您的问题!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2019-10-24
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多