How can I append element to array wiht graphql

Hi, I’m using graphql with Dgraph2.0.
Here is my schema:

type User {
    name String! @id
    interest [String!]
}

Then, how can I add an element to the “interest” array?
I tried something like this:

mutation {
    updateUser(input: {
        filter: {name: {eq:"Somebody"}},
        set:{interest: append("football")}
    }) {
            user{
                name
                interest 
            }
        }
}

But it didn’t work, so how can I make the mutation with graphql?
I don’t want to write the entire array like this: set:{interest:["cook", "reading", "football"]}, just want to append element what I want.

2 Likes

Oh, my fault.
It’s very easy to append element, just set: {interest: ["football"]}, it will add element “football” to interest, not just set the interest to ["football"].
I inspire by graphql±doc – “A set operation adds to the list of values. The order of the stored values is non-deterministic.”

3 Likes

By the way, remove: {interest:[""]} to empty the array.

1 Like

Thanks @Wisgon… BTW for anyone searching manipulating arrays in graphql, an idiom I’ve developed is to chain mutations in an update to first clear arrays, then “rewrite” them, for instance:

mutation updateLocation($id: ID!, $location: LocationPatch!) {
  # clear existing address lines (ensure new/existing lines are in LocationPatch)
  clearAddressesLines: updateLocation(input: {filter: {id: [$id]}, remove: {addresses: [""]}}) {
    location {
      id
    }
  }
  updateLocation(input: {filter: {id: [$id]}, set: $location}) {
    location {
      id
      addresses
      locality
      region
      postcode
    }
  }
}

1 Like