Last active
July 18, 2018 14:07
-
-
Save thewraven/349e5ad6426090a15ad220d9a2a2b730 to your computer and use it in GitHub Desktop.
Updating a nested field into an array using r.Branch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
r "gopkg.in/dancannon/gorethink.v3" | |
) | |
type Commentary struct { | |
From string `gorethink:"from"` | |
Recid string `gorethink:"recid"` | |
Subject string `gorethink:"subject"` | |
} | |
type Post struct { | |
ID string `gorethink:"id,omitempty"` | |
Comments []Commentary `gorethink:"comments"` | |
Subject string `gorethink:"subject"` | |
Author string `gorethink:"author"` | |
} | |
var initialPost = Post{ | |
Subject: "My name is Bob and it's the worst ever", | |
Author: "Bob", | |
Comments: []Commentary{ | |
Commentary{From: "Hulk", Recid: "ddef-a341", Subject: "I'm hulk!"}, | |
Commentary{From: "Thor", Recid: "aced-a112", Subject: "I'm thor"}, | |
}, | |
} | |
var editedCommmentary = Commentary{ | |
From: "Hulk", | |
Recid: "ddef-a341", | |
Subject: "I'm hulk! Arggggh!", | |
} | |
type term map[string]interface{} | |
func main() { | |
session, err := r.Connect(r.ConnectOpts{ | |
Database: "test", | |
}) | |
tablePosts := "posts" | |
if err != nil { | |
panic(err) | |
} | |
recID := editedCommmentary.Recid | |
result, err := r.Table(tablePosts).Insert(initialPost).RunWrite(session) | |
if err != nil { | |
panic(err) | |
} | |
postID := initialPost.ID | |
if len(result.GeneratedKeys) > 0 { | |
postID = result.GeneratedKeys[0] | |
} | |
response, err := r.Table(tablePosts).Get(postID).Update(term{ | |
"comments": r.Row.Field("comments").Map(func(c r.Term) interface{} { | |
return r.Branch(c.Field("recid").Eq(recID), editedCommmentary, c) | |
}), | |
}).RunWrite(session) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(response) | |
cursor, err := r.Table(tablePosts).Get(postID).Run(session) | |
if err != nil { | |
panic(err) | |
} | |
err = cursor.One(&initialPost) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(initialPost) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment