John
John

Reputation: 634

Data modeling in datastore

I just started using Datastore, so I'm still not sure about few things.

I have the fallowing entities:

Property: {ID, number, name, long, lat}

Address: {name, postCodeType}

City: {name}

Country: {name}

User: {name, username}

So the logic behind this is that a User will have multiple properties, which means that a property will hold a user key.

As described above the Property has some properties, but I am not sure on how to associate the address city and country.

I think a solution will be to store the keys for those 3 entities in the property entity.

type Property struct {   
  ID         int64   `json:"id" datastore:"-"`
  Number     int8    `json:"number"`
  Name       string  `json:"name"`
  Long       float64 `json:"long"`
  Lat        float64 `json:"lat"`
  AddressKey *datastore.Key
  CityKey    *datastore.Key
  CountryKey *datastore.Key
  UserKey    *datastore.Key
  CreatedAt  time.Time
}

Is my attempt from above a good start or what do I need to do different.

Upvotes: 0

Views: 63

Answers (1)

Andrei Volgin
Andrei Volgin

Reputation: 41099

  1. A list of countries rarely changes, so most programmers use an enum (or a Goland equivalent) to represent countries, instead of creating entities in the datastore. You can use ether 2-letter or 3-letter country codes, and simply save a country code as a string property within an Address entity. The enum can also return a full display name of a country based on its code.

  2. I also don't see a reason to create an entity for cities, although it can be done, if really necessary. Usually, a city is saved as a string property, indexed if necessary, within an Address entity.

This means that your Address entity may look like:

Address: {name, street, city, country, postCode}
  1. Going further, if each property has only one address, you may not need the Address entity at all. Which leads us to a very simple solution:

    type Property struct {   
      ID         int64   `json:"id" datastore:"-"`
      Number     int8    `json:"number"`
      Name       string  `json:"name"`
      Long       float64 `json:"long"`
      Lat        float64 `json:"lat"`
      Street     string  `json:"street"`
      City       string  `json:"city"`
      Country    string  `json:"country"`
      PostCode   string  `json:"postCode"`
      UserKey    *datastore.Key
      CreatedAt  time.Time
    }
    

Upvotes: 3

Related Questions