如何将地图存储到Firestore数组

时间:2019-08-26 21:49:06

标签: arrays firebase flutter google-cloud-firestore maps

我在abc集合中有xyz文档。

  • 我想在文档xyz 内的数组中添加映射

我可以使用此代码添加单个数组项

CollectionReference collection = this.collection(collection);
DocumentReference ref = collection.document(document);
ref.setData({"data": FieldValue.arrayUnion(values)});

此处数据是父数组。

但是当我尝试添加另一个地图时,firestore 替换了索引 0 的值,它没有将地图添加到下一个索引是指索引1,2,3或.....

让我们看一下例子 这是地图

    values = {
        "tokens": "99",
        "title": "Cleaning",
        "location": {"  lat": "34.4333", "lng": "53.4343"},
        "id": "gVnGE5ZPRnQ8HYQq7dvT",
        "client": "LFBXXj7Zi0xOr0FqBGID",
        "date": "22/8/2019",
        "message": "request message...",
        "budget": "150",
        "details": {
        "  When would you like to have the cleaners over?":
            "week",
        "What type of cleaning package would you prefer?":
            "answer for the type of clean",
        "Do you need the cleaning tools and materials?":
            "false",
        "What time do you prefer to have the cleaners over?":
            "8/20/2019"
        }
    }

,并且我想在每次将数据发送到firesotre时将其添加为新的数组项

例如

    onTap() {
        CollectionReference collection = this.collection(collection);
        DocumentReference ref = collection.document(document);
        ref.setData({"value": FieldValue.arrayUnion(values)});
    }

这是代码

    var values = {
        "tokens": "99",
        "title": "Cleaning",
        "location": {"  lat": "34.4333", "lng": "53.4343"},
        "id": "gVnGE5ZPRnQ8HYQq7dvT",
        "client": "LFBXXj7Zi0xOr0FqBGID",
        "date": "22/8/2019",
        "message": "request message...",
        "budget": "150",
        "details": {
        "  When would you like to have the cleaners over?":
            "week",
        "What type of cleaning package would you prefer?":
            "answer for the type of clean",
        "Do you need the cleaning tools and materials?":
            "false",
        "What time do you prefer to have the cleaners over?":
            "8/20/2019"
        }
    }

    onTap() {
        CollectionReference collection = this.collection(collection);
        DocumentReference ref = collection.document(document);
        ref.setData({"value": FieldValue.arrayUnion(values)});
    }

1 个答案:

答案 0 :(得分:2)

您正在使用setData函数来覆盖现有值。您需要改用updateData函数,该函数会将值添加到现有数组中。只需将您的onTap函数更改为此:

onTap() {
        CollectionReference collection = this.collection(collection);
        DocumentReference ref = collection.document(document);
        ref.updateData({"value": FieldValue.arrayUnion(values)});
}