【问题标题】:add a field in array in firebase without removing other fields in firebase [duplicate]在firebase中的数组中添加一个字段而不删除firebase中的其他字段[重复]
【发布时间】:2021-10-04 02:15:32
【问题描述】:

我想在数组中添加一个新字段,但是当我尝试添加一个新字段时,它将删除其余部分并仅添加剩余部分。 我试过了,但没有用

 collectionRef
        .doc("userIdLalit")
        .collection("stories")
        .doc("BHUCC3ewEeByJ6U68ygJ")
        .update(
      {
        "reactionModel": {
          "user": [
            {"fourth element": "Sam"},
          ],
        }
      },
    );

此代码将删除第 0 和第 1 个元素并添加第四个元素,但每当我添加新字段时我都想要它们

我尝试使用 set 方法合并 true 但没有用

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您可以使用FieldValue.arrayUnion() 将新项目推送到数组中:

    collectionRef
      .doc("userIdLalit")
      .collection("stories")
      .doc("BHUCC3ewEeByJ6U68ygJ")
      .update({
        "reactionModel.user":  FieldValue.arrayUnion({"fourth element": "Sam"})
      });
    

    此外,数组嵌套在地图中,因此您必须使用点符号来更新它,即"reactionModel.user"

    【讨论】:

      猜你喜欢
      • 2022-12-08
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2022-11-12
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多