Search code examples
gogoogle-cloud-platformgoogle-cloud-datastore

How to not store __key__ in datastore


Here is how i am persisting data to datastore

type UserDetails struct {
    UserID    string `datastore:"__key__"`
    Name      string
    UserEmail string
}

func (c DataStoreClient) Put(ctx context.Context, orgID string, ud *UserDetails) (id int64, err error) {
    key := datastore.NameKey(userKind, ud.UserID, nil)
    key.Namespace = orgID

    k, err := c.client.Put(ctx, key, ud)
    if err != nil {
        return 0, err
    }
    return k.ID, nil
}

func (ud *DataStoreUserDetails) Save() ([]datastore.Property, error) {
    return datastore.SaveStruct(ud)
}

func (ud *DataStoreUserDetails) LoadKey(k *datastore.Key) error {
    ud.UserID = k.Name
    return nil
}

func (ud *DataStoreUserDetails) Load(ps []datastore.Property) error {
    return datastore.LoadStruct(ud, ps)
}

When i call Put method, i am able to store UserDetails successfully in datastore. But, along with all the columns in UserDetails, I can also see __key__ column. I don't want that. I want to keep UserID as the key for this table.

How can i do that?


Solution

  • Use the datastore name "-" to ignore the field when saving or loading the entity.

    type UserDetails struct {
        UserID    string `datastore:"-"` // <-- change on this line
        Name      string
        UserEmail string
    }