【问题标题】:Firebase push JSON Object to JSON ArrayFirebase 将 JSON 对象推送到 JSON 数组
【发布时间】:2021-04-26 20:22:50
【问题描述】:

我在 Firebase 中使用以下方法创建了文档:

'tasks': [
    {
      'id': 1,
      'type': TaskType.ImportantAndNotUrgent.toTypeName(),
      'name': 'Just added this',
      'deadline': DateTime.now().add(Duration(days: 1)).toIso8601String(),
      'tags': [
        {
          'id': 1,
          'name': 'addTask method'
        },
      ],
    }
  ],

我想将新对象推送到“任务”数组,所以它看起来像:

'tasks': [
    {
      //First object
    },
    {
      //Second object
    },
  ],

我有此文档的 DocumentReference,但我不知道如何推送新值。调用 update() 方法会替换“任务”而不是推送给它。

我的代码:

Future addTask(String uid, TaskModel task) async {
var taskCollection = firestore.collection('usersData')
    .doc(uid).collection('tasks').doc('ImportantAndNotUrgent');
print("Adding task");
taskCollection.update({
  'tasks':
    {
      'id': 1,
      'type': TaskType.ImportantAndNotUrgent.toTypeName(),
      'name': 'Just added this',
      'deadline': DateTime.now().add(Duration(days: 1)).toIso8601String(),
      'tags': [
        {
          'id': 1,
          'name': 'addTask method'
        },
      ],
    }
})
    .then((value) => print("Successfully added task"))
    .catchError((error) => print("Failed to add task: $error"));
}

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    arrayUnion,像这样:

     .update({
      'tasks': FieldValue.arrayUnion([{
          'id': 1,
          'type': TaskType.ImportantAndNotUrgent.toTypeName(),
          'name': 'Just added this',
          'deadline': DateTime.now().add(Duration(days: 1)).toIso8601String(),
          'tags': [
            {
              'id': 1,
              'name': 'addTask method'
            },
          ],
        }]),       
       })
    

    【讨论】:

    • 感谢您的回答,它成功了。你知道如何将更多对象添加到“标签”吗?
    • FieldValue.arrayUnion([{tag1 data}, {tag2 data} , {tag3 data}])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多