Nested structs on GAE datastore using Go

2020-04-05 07:30发布

I'm trying to figure out how to get nested structs to work with GAE datastore using Go. I know the datastore doesn't specifically support nested structs. I need to find a simple way of getting user information to go with a post when it is sent out to a user as JSON.

One thing I thought of was to put two fields for the user. One for the ID/key referencing to user and another one for the user type struct which would be added there when the post is loaded from the datastore. Extra fields seem silly so I'm hoping there is a better solution for this.

There are two entity types or structs: POST and USER

Posts need to contain information about the user who made the post.

The structure for the JSON I'm going to output for users is as follows:

  • POST
    • field1
    • field2
    • USER
      • user_field1
      • user_Field2

2条回答
淡お忘
2楼-- · 2020-04-05 08:11

Go's appengine datastore api provides the PropertyLoadSaver interface for this sort of thing: https://developers.google.com/appengine/docs/go/datastore/reference#PropertyLoadSaver

You structure your struct however you want and then implement the Load and Save methods of that interface to populate it correctly. It means you write the serialization code yourself but it gives you full freedom in how you structure your data.

This will allow you still filter over the fields and have a nested struct.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-04-05 08:18

The python runtime has the ndb library which supports nested structures like this. Go does not, so I can think of two solutions:

  1. In the POST kind, have a user field that is a key, referencing a USER kind with the necessary fields. Requires two fetches and roundtrips.
  2. Make a user field in the POST kind that is a blob. The blob is a string that is [de]serialized in go. This means you can't search or filter on any of the user data, but it also allows you to store everything in one entity.

You should use these based on the needs of your app. If you need users to be a real thing, use 1. If users aren't objects you need to work with (i.e., just data to display), you can use 2.

查看更多
登录 后发表回答