简体   繁体   English

Firestore Swift:通过更新数据添加多个子地图

[英]Firestore Swift: Adding multiple child maps by updating data

I've come across a scenario where I want something structured like this:我遇到了一个场景,我想要这样的结构: 在此处输入图像描述

I tried to do set the data by doing我试图通过做来设置数据

var mapValues: [String : Any] {
            return [ user_uuid! :
                        [
                            "name" : AuthViewModel().decodeUserInfo()?.displayName! as Any,
                            "checkInTime" : "",
                            "checkOutTime" : "",
                        ]
            ]
        }
            
db.collection("Collection")
     .document(eventID).updateData(["attendees" : mapValues])

However, the problem with this is that it does not "append" a new child to the map.但是,问题在于它不会将新子“附加”到 map。 Instead, I am overriding it.相反,我正在覆盖它。 Is there a way to add a new "element" without wiping everything else?有没有办法在不擦除其他所有内容的情况下添加新的“元素”? I am looking for something that works similar to FieldValue.arrayUnion , but without changing my structure to an array.我正在寻找类似于FieldValue.arrayUnion的东西,但没有将我的结构更改为数组。

When you call updateData the database writes only the fields that you specify, but for those fields any existing value in the database is indeed replaced.当您调用updateData ,数据库仅写入您指定的字段,但对于这些字段,数据库中的任何现有值确实会被替换。

If you want to add an item to the array and all your items are unique, you can use the array-union operator .如果要向数组中添加一个项目并且所有项目都是唯一的,则可以使用array-union运算符

Note that it is never possible to update a value in an array item, so if you want to say update the name for an existing item, you will have to:请注意,永远不可能更新数组项中的值,因此如果您想说更新现有项的name ,则必须:

  1. Read the array from the document.从文档中读取数组。
  2. Update the array in your application code.更新应用程序代码中的数组。
  3. Write the entire array field back to the database.将整个数组字段写回数据库。

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

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