In Node.js, I can save a nested json object and when I view my entity, it is represented as a nested entity.
ds.save({
ds.key(['degrees']),
data: {
name: "AA Math",
units: "3-5",
terms: [{
name: "term1",
courses: [{
name: "MATH 160",
units: "3.0"
},{
name: "ENGL 210",
units: "4.0"
}]
}]
}, function(err) {
if (err) console.log(err);
});
Now I'm trying to rewrite the server using GO, but it does not seem to accept a nested json as an entity. I know that I could save it as an array of blobs, []byte, or even a string and decode it on the retrieval, however, most of my data already is stored as json objects in the Datastore and it would be so much nicer to store it in the same manner.
I have already implemented the PropertyLoadSaver to convert the jsons to structs coming into GO, but when trying to save as a nested Entity I get a 'datastore: invalid Value type for a Property with Name \"terms\"' error. Is there anyway of saving a array json object into the Datastore in GO?
I see that in the docs that a Property can be a nested Entity but can't figure out how to implement it.
// Property is a name/value pair plus some metadata. A datastore entity's
// contents are loaded and saved as a sequence of Properties. An entity can
// have multiple Properties with the same name, provided that p.Multiple is
// true on all of that entity's Properties with that name.
type Property struct {
// Name is the property name.
Name string
// Value is the property value. The valid types are:
// - int64
// - bool
// - string
// - float64
// - ByteString
// - Key
// - time.Time
// - appengine.BlobKey
// - appengine.GeoPoint
// - []byte (up to 1 megabyte in length)
// - Entity (representing a nested struct)
Edit: So it looks like my issue is due to the fact that I have a Slice of a Slice, but Node.js doesn't see this as an issue.
@MoreThanCarbon for a typical use case, you shouldn't need to implement PropertyLoadSaver just to convert json to nested entity.
can you paste your go code?
Hey @anthmgoogle, I just moved teams. @jba is your go-to for go datastore things now :)
I wrote these Go types for your data:
type Course struct {
Name string
Units string
Terms []Term
}
type Term struct {
Name string
Courses []Course
}
Then I created a Course value:
var course = &Course{
Name: "AA Math",
Units: "3-5",
Terms: []Term{
{
Name: "term1",
Courses: []Course{
{Name: "MATH 160", Units: "3.0"},
{Name: "ENGL 210", Units: "4.0"},
},
},
},
}
I put it into Datastore with this code:
k, err := c.Put(ctx, datastore.IncompleteKey("Courses", nil), course)
if err != nil {
log.Fatal("put: ", err)
}
I was then able to successfully read it with:
var got Course
if err := c.Get(ctx, k, &got); err != nil {
log.Fatal("get: ", err)
}
Most helpful comment
I wrote these Go types for your data:
Then I created a
Coursevalue:I put it into Datastore with this code:
I was then able to successfully read it with: