How to add object in an array?

I’m experimenting with Slash GraphQL’s toto app tutorial.

type Task {
  id: ID!
  title: String! @search(by: [fulltext])
  completed: Boolean! @search
  user: User!
}
type User {
  username: String! @id @search(by: [hash])
  name: String @search(by: [exact])
  tasks: [Task] @hasInverse(field: user)
}

I get this error when I try adding a new task to alice@dgraph.io.
Mutation

mutation addTaskToUser {
  updateUser(input: {
    filter: {username: {eq: "alice@dgraph.io"}},
    set: {
      tasks: [{
        title: "new task",
        completed: true,
        id: "0x8"
      }]
    }
  }) {
    user {
      username
      name
      tasks {
        id
        title
        completed
      }
    }
  }
}

Error message

{
  "errors": [
    {
      "message": "couldn't rewrite query for mutation updateUser because ID \"0x8\" isn't a Task"
    }
  ],
  "data": {
    "updateUser": null
  },
  "extensions": {
    "touched_uids": 8,
    "tracing": {
      "version": 1,
      "startTime": "2020-10-23T08:27:17.432688116Z",
      "endTime": "2020-10-23T08:27:17.439684393Z",
      "duration": 6996277,
      "execution": {
        "resolvers": [
          {
            "path": [
              "updateUser"
            ],
            "parentType": "Mutation",
            "fieldName": "updateUser",
            "returnType": "UpdateUserPayload",
            "startOffset": 110433,
            "duration": 6871341,
            "dgraph": [
              {
                "label": "mutation",
                "startOffset": 194936,
                "duration": 3776358
              },
              {
                "label": "query",
                "startOffset": 0,
                "duration": 0
              }
            ]
          }
        ]
      }
    },
    "queryCost": 1
  }
}

The mutation updates an existing task if the task ID matches, however I want to add a new task to the user.

Welcome @secretshardul!

Your mutation should work after removing the “id” field in the task node as below. A new task will be added to the existing user. ID will be generated by Dgraph.

mutation addTaskToUser {
  updateUser(input: {
    filter: {username: {eq: "alice@dgraph.io"}},
    set: {
      tasks: [{
        title: "new task",
        completed: true
        
      }]
    }
  }) {
    user {
      username
      name
      tasks {
        id
        title
        completed
      }
    }
  }
}

You can then query for data as below:

query MyQuery {
  getUser(username: "alice@dgraph.io") {
    username
    tasks {
      id
      title
      completed
    }
  }
}

Result I got on Slash.

{
  "data": {
    "getUser": {
      "username": "alice@dgraph.io",
      "tasks": [
        {
          "id": "0x4e22",
          "title": "new task",
          "completed": true
        }
      ]
    }
  }
1 Like

Great thanks!