How to get Uids after updating the node?

I am using the Upsert to Create or Update the node with Go Lang.

Here is my code

dg, cancel := getDgraphClient()
defer cancel()
ctx := context.Background()
req := &api.Request{CommitNow: true}
req.Query = `
		{
			me(func: eq(name, "Alice")) {
				...fragmentA
			}
		}
		fragment fragmentA {
			v as uid
		}
	`
pb, err := json.Marshal(User{Uid: "uid(v)", Name: "Alice", Email: "user@mail.com"})
if err != nil {
    log.Fatal(err)
}
mu := &api.Mutation{SetJson: pb}
req.Mutations = []*api.Mutation{mu}
if resp, err := dg.NewTxn().Do(ctx, req); err != nil {
    log.Fatal(err)
}

return resp.Uids

When a node is created then I am getting those Uids but when it is updated then I am not getting Uids in response.

Is there any way I will get Uids in both conditions?

Hi Sandeep,
We can get the UIDs in both conditions, but in different parts of the “resp” variable. If the node has already been created, the uid will be in the response json and needs to be picked from there. This is documented here. Quoting from the doc:

If we run the same mutation again, the data would just be overwritten, and no new uid is created. Note that the uids map is empty in the result when the mutation is executed again and the data map (key q ) contains the uid that was created in the previous upsert.

{
  "data": {
    "q": [
      {
        "uid": "0x1",
        "name": "first last"
      }
    ],
    "code": "Success",
    "message": "Done",
    "uids": {}
  },
  "extensions": {...}
}

In your example, fmt.Printf("%s\n", resp.Json) would yield:

{"me":[{"uid":"0xb"}]}
1 Like