next_99
next_99

Reputation: 35

Firebase push JSON Object to JSON Array

I have created document in Firebase using:

'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'
        },
      ],
    }
  ],

I want to push new object to 'tasks' array, so it would look like:

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

I've got DocumentReference to this document, but I don't know how to push new value. Calling update() method replaces 'tasks' instead of pushing to it.

My code:

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"));
}

Upvotes: 0

Views: 343

Answers (1)

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

You arrayUnion, like this:

 .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'
        },
      ],
    }]),       
   })

Upvotes: 1

Related Questions